org.eclipse.jetty.server.UserIdentity Java Examples

The following examples show how to use org.eclipse.jetty.server.UserIdentity. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SdcHashLoginService.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Override
protected String[] loadRoleInfo(UserPrincipal user)
{
  UserIdentity id = _userStore.getUserIdentity(user.getName());
  if (id == null)
    return null;


  Set<RolePrincipal> roles = id.getSubject().getPrincipals(RolePrincipal.class);
  if (roles == null)
    return null;

  return roles.stream()
      .map(RolePrincipal::getName)
      .filter(role -> !role.startsWith(EMAIL_PREFIX))
      .filter(role -> !role.startsWith(GROUP_PREFIX))
      .toArray(String[]::new);
}
 
Example #2
Source File: JwtLoginServiceTest.java    From cruise-control with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testValidateTokenSuccessfully() throws Exception {
  UserStore testUserStore = new UserStore();
  testUserStore.addUser(TEST_USER, SecurityUtils.NO_CREDENTIAL, new String[] {"USER"});
  TokenGenerator.TokenAndKeys tokenAndKeys = TokenGenerator.generateToken(TEST_USER);
  JwtLoginService loginService = new JwtLoginService(new UserStoreAuthorizationService(testUserStore), tokenAndKeys.publicKey(), null);

  SignedJWT jwtToken = SignedJWT.parse(tokenAndKeys.token());
  HttpServletRequest request = mock(HttpServletRequest.class);
  expect(request.getAttribute(JwtAuthenticator.JWT_TOKEN_REQUEST_ATTRIBUTE)).andReturn(tokenAndKeys.token());

  replay(request);
  UserIdentity identity = loginService.login(TEST_USER, jwtToken, request);
  verify(request);
  assertNotNull(identity);
  assertEquals(TEST_USER, identity.getUserPrincipal().getName());
}
 
Example #3
Source File: JwtLoginServiceTest.java    From cruise-control with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testRevalidateTokenPasses() throws Exception {
  UserStore testUserStore = new UserStore();
  testUserStore.addUser(TEST_USER, SecurityUtils.NO_CREDENTIAL, new String[] {"USER"});
  TokenGenerator.TokenAndKeys tokenAndKeys = TokenGenerator.generateToken(TEST_USER);
  JwtLoginService loginService = new JwtLoginService(new UserStoreAuthorizationService(testUserStore), tokenAndKeys.publicKey(), null);

  SignedJWT jwtToken = SignedJWT.parse(tokenAndKeys.token());
  HttpServletRequest request = mock(HttpServletRequest.class);
  expect(request.getAttribute(JwtAuthenticator.JWT_TOKEN_REQUEST_ATTRIBUTE)).andReturn(tokenAndKeys.token());

  replay(request);
  UserIdentity identity = loginService.login(TEST_USER, jwtToken, request);
  verify(request);
  assertNotNull(identity);
  assertEquals(TEST_USER, identity.getUserPrincipal().getName());
  assertTrue(loginService.validate(identity));
}
 
Example #4
Source File: TrustedProxyLoginServiceTest.java    From cruise-control with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testInvalidAuthServiceUser() {
  ConfigurableSpnegoLoginService mockSpnegoLoginService = mock(ConfigurableSpnegoLoginService.class);

  SpnegoUserPrincipal servicePrincipal = new SpnegoUserPrincipal(TEST_SERVICE_USER, ENCODED_TOKEN);
  Subject subject = new Subject(true, Collections.singleton(servicePrincipal), Collections.emptySet(), Collections.emptySet());
  SpnegoUserIdentity result = new SpnegoUserIdentity(subject, servicePrincipal, null);
  expect(mockSpnegoLoginService.login(anyString(), anyObject(), anyObject())).andReturn(result);

  TestAuthorizer userAuthorizer = new TestAuthorizer(TEST_USER);

  HttpServletRequest mockRequest = mock(HttpServletRequest.class);
  expect(mockRequest.getParameter(DO_AS)).andReturn(TEST_USER);
  replay(mockSpnegoLoginService);

  TrustedProxyLoginService trustedProxyLoginService = new TrustedProxyLoginService(mockSpnegoLoginService, userAuthorizer);
  UserIdentity doAsIdentity = trustedProxyLoginService.login(null, ENCODED_TOKEN, mockRequest);
  assertNotNull(doAsIdentity);
  assertFalse(((SpnegoUserIdentity) doAsIdentity).isEstablished());
}
 
Example #5
Source File: TrustedProxyLoginServiceTest.java    From cruise-control with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testNoDoAsUser() {
  ConfigurableSpnegoLoginService mockSpnegoLoginService = mock(ConfigurableSpnegoLoginService.class);

  SpnegoUserPrincipal servicePrincipal = new SpnegoUserPrincipal(TEST_SERVICE_USER, ENCODED_TOKEN);
  UserIdentity serviceDelegate = mock(UserIdentity.class);
  Subject subject = new Subject(true, Collections.singleton(servicePrincipal), Collections.emptySet(), Collections.emptySet());
  SpnegoUserIdentity result = new SpnegoUserIdentity(subject, servicePrincipal, serviceDelegate);
  expect(mockSpnegoLoginService.login(anyString(), anyObject(), anyObject())).andReturn(result);

  TestAuthorizer userAuthorizer = new TestAuthorizer(TEST_USER);

  HttpServletRequest mockRequest = mock(HttpServletRequest.class);
  replay(mockSpnegoLoginService);

  TrustedProxyLoginService trustedProxyLoginService = new TrustedProxyLoginService(mockSpnegoLoginService, userAuthorizer);
  UserIdentity doAsIdentity = trustedProxyLoginService.login(null, ENCODED_TOKEN, mockRequest);
  assertNotNull(doAsIdentity);
  assertNotNull(doAsIdentity.getUserPrincipal());
  assertNull(doAsIdentity.getUserPrincipal().getName());
  assertFalse(((SpnegoUserIdentity) doAsIdentity).isEstablished());
}
 
Example #6
Source File: TrustedProxyLoginServiceTest.java    From cruise-control with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testSuccessfulAuthentication() {
  ConfigurableSpnegoLoginService mockSpnegoLoginService = mock(ConfigurableSpnegoLoginService.class);

  SpnegoUserPrincipal servicePrincipal = new SpnegoUserPrincipal(TEST_SERVICE_USER, ENCODED_TOKEN);
  UserIdentity serviceDelegate = mock(UserIdentity.class);
  Subject subject = new Subject(true, Collections.singleton(servicePrincipal), Collections.emptySet(), Collections.emptySet());
  SpnegoUserIdentity result = new SpnegoUserIdentity(subject, servicePrincipal, serviceDelegate);
  expect(mockSpnegoLoginService.login(anyString(), anyObject(), anyObject())).andReturn(result);

  TestAuthorizer userAuthorizer = new TestAuthorizer(TEST_USER);

  HttpServletRequest mockRequest = mock(HttpServletRequest.class);
  expect(mockRequest.getParameter(DO_AS)).andReturn(TEST_USER);

  replay(mockSpnegoLoginService, mockRequest);

  TrustedProxyLoginService trustedProxyLoginService = new TrustedProxyLoginService(mockSpnegoLoginService, userAuthorizer);
  UserIdentity doAsIdentity = trustedProxyLoginService.login(null, ENCODED_TOKEN, mockRequest);
  assertNotNull(doAsIdentity);
  assertNotNull(doAsIdentity.getUserPrincipal());
  assertEquals(doAsIdentity.getUserPrincipal().getName(), TEST_USER);
  assertEquals(((TrustedProxyPrincipal) doAsIdentity.getUserPrincipal()).servicePrincipal(), servicePrincipal);
}
 
Example #7
Source File: JwtLoginServiceTest.java    From cruise-control with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testRevalidateTokenFails() throws Exception {
  UserStore testUserStore = new UserStore();
  testUserStore.addUser(TEST_USER, SecurityUtils.NO_CREDENTIAL, new String[] {"USER"});
  Instant now = Instant.now();
  TokenGenerator.TokenAndKeys tokenAndKeys = TokenGenerator.generateToken(TEST_USER, now.plusSeconds(10).toEpochMilli());
  Clock fixedClock = Clock.fixed(now, ZoneOffset.UTC);
  JwtLoginService loginService = new JwtLoginService(
      new UserStoreAuthorizationService(testUserStore), tokenAndKeys.publicKey(), null, fixedClock);

  SignedJWT jwtToken = SignedJWT.parse(tokenAndKeys.token());
  HttpServletRequest request = mock(HttpServletRequest.class);
  expect(request.getAttribute(JwtAuthenticator.JWT_TOKEN_REQUEST_ATTRIBUTE)).andReturn(tokenAndKeys.token());

  replay(request);
  UserIdentity identity = loginService.login(TEST_USER, jwtToken, request);
  verify(request);
  assertNotNull(identity);
  assertEquals(TEST_USER, identity.getUserPrincipal().getName());
  loginService.setClock(Clock.offset(fixedClock, Duration.ofSeconds(20)));
  assertFalse(loginService.validate(identity));
}
 
Example #8
Source File: SpnegoUserStoreAuthorizationServiceTest.java    From cruise-control with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testPrincipalNames() {
  UserStore users = new UserStore();
  users.addUser(TEST_USER, SecurityUtils.NO_CREDENTIAL, new String[] { DefaultRoleSecurityProvider.ADMIN });
  UserStoreAuthorizationService usas = new SpnegoUserStoreAuthorizationService(users);

  UserIdentity result = usas.getUserIdentity(null, TEST_USER + "/host@REALM");
  assertNotNull(result);
  assertEquals(TEST_USER, result.getUserPrincipal().getName());

  result = usas.getUserIdentity(null, TEST_USER + "@REALM");
  assertNotNull(result);
  assertEquals(TEST_USER, result.getUserPrincipal().getName());

  result = usas.getUserIdentity(null, TEST_USER + "/host");
  assertNotNull(result);
  assertEquals(TEST_USER, result.getUserPrincipal().getName());

  result = usas.getUserIdentity(null, TEST_USER);
  assertNotNull(result);
  assertEquals(TEST_USER, result.getUserPrincipal().getName());
}
 
Example #9
Source File: CustomAuthHttpServerTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Override public RemoteUserExtractor getRemoteUserExtractor() {
  return new RemoteUserExtractor() {
    @Override public String extract(HttpServletRequest request)
        throws RemoteUserExtractionException {
      methodCallCounter3++;
      if (request instanceof Request) {
        Authentication authentication = ((Request) request).getAuthentication();
        if (authentication instanceof UserAuthentication) {
          UserIdentity userIdentity = ((UserAuthentication) authentication).getUserIdentity();
          return userIdentity.getUserPrincipal().getName();
        }
      }
      throw new RemoteUserExtractionException("Request doesn't contain user credentials.");
    }
  };
}
 
Example #10
Source File: AuthenticationResourceFilter.java    From emodb with Apache License 2.0 6 votes vote down vote up
/**
 * Certain aspects of the container, such as logging, need the authentication information to behave properly.
 * This method updates the request with the necessary objects to recognize the authenticated user.
 */
private void setJettyAuthentication(Subject subject) {
    // In unit test environments there may not be a current connection.  If any nulls are encountered
    // then, by definition, there is no container to update.
    HttpConnection connection = HttpConnection.getCurrentConnection();
    if (connection == null) {
        return;
    }
    Request jettyRequest = connection.getHttpChannel().getRequest();
    if (jettyRequest == null) {
        return;
    }

    // This cast down is safe; subject is always created with this type of principal
    PrincipalWithRoles principal = (PrincipalWithRoles) subject.getPrincipal();
    UserIdentity identity = principal.toUserIdentity();

    jettyRequest.setAuthentication(new UserAuthentication(SecurityContext.BASIC_AUTH, identity));
}
 
Example #11
Source File: FederationAuthenticator.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private boolean isTokenExpired(FedizContext fedConfig, UserIdentity userIdentity) {
    if (fedConfig.isDetectExpiredTokens()) {
        try {
            FederationUserIdentity fui = (FederationUserIdentity)userIdentity;
            Instant tokenExpires = fui.getExpiryDate();
            if (tokenExpires == null) {
                LOG.debug("Token doesn't expire");
                return false;
            }

            Instant currentTime = Instant.now();
            if (!currentTime.isAfter(tokenExpires)) {
                return false;
            } else {
                LOG.warn("Token already expired. Clean up and redirect");

                return true;
            }
        } catch (ClassCastException ex) {
            LOG.warn("UserIdentity must be instance of FederationUserIdentity");
            throw new IllegalStateException("UserIdentity must be instance of FederationUserIdentity");
        }
    }

    return false;
}
 
Example #12
Source File: SSOAuthenticationUser.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Override
public UserIdentity getUserIdentity() {
  return new UserIdentity() {
    @Override
    public Subject getSubject() {
      return new Subject(true, ImmutableSet.of(principal), Collections.emptySet(), Collections.emptySet());
    }

    @Override
    public Principal getUserPrincipal() {
      return principal;
    }

    @Override
    public boolean isUserInRole(String s, Scope scope) {
      return principal.getRoles().contains(s);
    }
  };
}
 
Example #13
Source File: ActivationAuthenticator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Override
public UserIdentity getUserIdentity() {
  final UserIdentity userIdentity = user.getUserIdentity();
  return new UserIdentity() {
    @Override
    public Subject getSubject() {
      return userIdentity.getSubject();
    }

    @Override
    public Principal getUserPrincipal() {
      return userIdentity.getUserPrincipal();
    }

    @Override
    public boolean isUserInRole(String role, Scope scope) {
      return ExpiredActivationUser.this.isUserInRole(scope, role);
    }
  };
}
 
Example #14
Source File: JwtLoginService.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public UserIdentity login(String username, Object credentials, ServletRequest request) {
  if (!(credentials instanceof SignedJWT)) {
    return null;
  }
  if (!(request instanceof HttpServletRequest)) {
    return null;
  }

  SignedJWT jwtToken = (SignedJWT) credentials;
  JWTClaimsSet claimsSet;
  boolean valid;
  try {
    claimsSet = jwtToken.getJWTClaimsSet();
    valid = validateToken(jwtToken, claimsSet, username);
  } catch (ParseException e) {
    JWT_LOGGER.warn(String.format("%s: Couldn't parse a JWT token", username), e);
    return null;
  }
  if (valid) {
    String serializedToken = (String) request.getAttribute(JwtAuthenticator.JWT_TOKEN_REQUEST_ATTRIBUTE);
    UserIdentity rolesDelegate = _authorizationService.getUserIdentity((HttpServletRequest) request, username);
    if (rolesDelegate == null) {
      return null;
    } else {
      return getUserIdentity(jwtToken, claimsSet, serializedToken, username, rolesDelegate);
    }
  } else {
    return null;
  }
}
 
Example #15
Source File: KeycloakSamlAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication createAuthentication(UserIdentity userIdentity, final Request request) {
    return new KeycloakAuthentication(getAuthMethod(), userIdentity) {
        @Override
        public void logout() {
            logoutCurrent(request);
        }
    };
}
 
Example #16
Source File: KeycloakSamlAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication createAuthentication(UserIdentity userIdentity, final Request request) {
    return new KeycloakAuthentication(getAuthMethod(), userIdentity) {
        @Override
        public void logout() {
            logoutCurrent(request);
        }
    };
}
 
Example #17
Source File: DrillSpnegoAuthenticator.java    From Bats with Apache License 2.0 5 votes vote down vote up
public UserIdentity login(String username, Object password, ServletRequest request) {
  final UserIdentity user = super.login(username, password, request);

  if (user != null) {
    final HttpSession session = ((HttpServletRequest) request).getSession(true);
    final Authentication cached = new SessionAuthentication(this.getAuthMethod(), user, password);
    session.setAttribute(SessionAuthentication.__J_AUTHENTICATED, cached);
  }

  return user;
}
 
Example #18
Source File: AbstractSamlAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public Authentication register(Request request, SamlSession samlSession) {
    Authentication authentication = request.getAuthentication();
    if (!(authentication instanceof KeycloakAuthentication)) {
        UserIdentity userIdentity = createIdentity(samlSession);
        authentication = createAuthentication(userIdentity, request);
        request.setAuthentication(authentication);
    }
    return authentication;
}
 
Example #19
Source File: SdcHashLoginService.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
protected UserPrincipal loadUserInfo(String userName)
{
  UserIdentity id = _userStore.getUserIdentity(userName);
  if (id != null)
  {
    return (UserPrincipal)id.getUserPrincipal();
  }

  return null;
}
 
Example #20
Source File: KeycloakJettyAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected Authentication createAuthentication(UserIdentity userIdentity, Request request) {
    return new KeycloakAuthentication(getAuthMethod(), userIdentity) {
        @Override
        public void logout() {
            logoutCurrent(HttpChannel.getCurrentHttpChannel().getRequest());
        }
    };
}
 
Example #21
Source File: JwtLoginServiceTest.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testFailAudienceValidation() throws Exception {
  UserStore testUserStore = new UserStore();
  testUserStore.addUser(TEST_USER, SecurityUtils.NO_CREDENTIAL, new String[] {"USER"});
  TokenGenerator.TokenAndKeys tokenAndKeys = TokenGenerator.generateToken(TEST_USER, Arrays.asList("A", "B"));
  JwtLoginService loginService = new JwtLoginService(
      new UserStoreAuthorizationService(testUserStore), tokenAndKeys.publicKey(), Arrays.asList("C", "D"));

  SignedJWT jwtToken = SignedJWT.parse(tokenAndKeys.token());
  HttpServletRequest request = mock(HttpServletRequest.class);

  UserIdentity identity = loginService.login(TEST_USER, jwtToken, request);
  assertNull(identity);
}
 
Example #22
Source File: JwtLoginServiceTest.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testFailExpirationValidation() throws Exception {
  UserStore testUserStore = new UserStore();
  testUserStore.addUser(TEST_USER, SecurityUtils.NO_CREDENTIAL, new String[] {"USER"});
  TokenGenerator.TokenAndKeys tokenAndKeys = TokenGenerator.generateToken(TEST_USER, 1L);
  JwtLoginService loginService = new JwtLoginService(new UserStoreAuthorizationService(testUserStore), tokenAndKeys.publicKey(), null);

  SignedJWT jwtToken = SignedJWT.parse(tokenAndKeys.token());
  HttpServletRequest request = mock(HttpServletRequest.class);

  UserIdentity identity = loginService.login(TEST_USER, jwtToken, request);
  assertNull(identity);
}
 
Example #23
Source File: ActivationAuthenticator.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isUserInRole(UserIdentity.Scope scope, String role) {
  if (allowedRoles.contains(role)) {
    return true;
  } else if (AuthzRole.ADMIN_ACTIVATION.equals(role) &&
             (user.isUserInRole(scope, AuthzRole.ADMIN) ||
              (user.isUserInRole(scope, AuthzRole.ADMIN_REMOTE)))) {
    return true;
  }
  return false;
}
 
Example #24
Source File: SecurityServiceLoginService.java    From sql-layer with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected UserIdentity loadUser(String username) {
    User user = securityService.getUser(username);
    if(user != null) {
        String password = (credentialType == CredentialType.BASIC) ? user.getBasicPassword() : user.getDigestPassword();
        List<String> roles = user.getRoles();
        return putUser(username, Credential.getCredential(password), roles.toArray(new String[roles.size()]));
    }
    return null;
}
 
Example #25
Source File: SecurityServiceLoginService.java    From sql-layer with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public UserIdentity login(String username, Object credentials) {
    long now = System.currentTimeMillis();
    if((now - lastCachePurge) > cacheMillis) {
        super._users.clear();
        lastCachePurge = now;
    }
    return super.login(username, credentials);
}
 
Example #26
Source File: AppEngineAuthentication.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public void logout(UserIdentity user) {
  // Jetty calls this on every request -- even if user is null!
  if (user != null) {
    log.fine("Ignoring logout call for: " + user);
  }
}
 
Example #27
Source File: SpnegoTestUtil.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
@Override public void handle(String target, Request baseRequest, HttpServletRequest request,
    HttpServletResponse response) throws IOException, ServletException {
  Authentication auth = baseRequest.getAuthentication();
  if (Authentication.UNAUTHENTICATED == auth) {
    throw new AssertionError("Unauthenticated users should not reach here!");
  }

  baseRequest.setHandled(true);
  UserAuthentication userAuth = (UserAuthentication) auth;
  UserIdentity userIdentity = userAuth.getUserIdentity();
  Principal userPrincipal = userIdentity.getUserPrincipal();

  response.getWriter().print("OK " + userPrincipal.getName());
  response.setStatus(200);
}
 
Example #28
Source File: HybridLoginService.java    From sql-layer with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public UserIdentity login(String username, Object credentials) {
    UserIdentity inner = delegate.login(username, credentials);
    if (inner == null)
        return null;
    String userName = inner.getUserPrincipal().getName();
    int at = userName.indexOf('@');
    if (at >= 0) userName = userName.substring(0, at);
    User user = securityService.getUser(userName);
    if (user == null)
        return inner;
    else
        return new WrappedUserIdentity(inner, user);
}
 
Example #29
Source File: MongoLoginService.java    From EDDI with Apache License 2.0 5 votes vote down vote up
private UserIdentity createUserIdentity(String username, Credential credential) {
    Principal userPrincipal = new AbstractLoginService.UserPrincipal(username, credential);
    Subject subject = new Subject();
    subject.getPrincipals().add(userPrincipal);
    subject.getPrivateCredentials().add(credential);
    subject.setReadOnly();
    return identityService.newUserIdentity(subject, userPrincipal, new String[]{"user"});
}
 
Example #30
Source File: FederationLoginService.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
public boolean validate(UserIdentity user) {
    try {
        FederationUserIdentity fui = (FederationUserIdentity)user;
        return fui.getExpiryDate().isAfter(Instant.now());
    } catch (ClassCastException ex) {
        LOG.warn("UserIdentity must be instance of FederationUserIdentity");
        throw new IllegalStateException("UserIdentity must be instance of FederationUserIdentity");
    }
}