下面列出了怎么用org.eclipse.jetty.server.UserIdentity的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
@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());
}
@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());
}
@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());
}
@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));
}
@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));
}
@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 + "/[email protected]");
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());
}
@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.");
}
};
}
/**
* 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));
}
@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);
}
};
}
@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);
}
};
}
@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);
}
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;
}
@Override
public Authentication createAuthentication(UserIdentity userIdentity, Request request) {
return new KeycloakAuthentication(getAuthMethod(), userIdentity) {
@Override
public void logout() {
logoutCurrent(HttpChannel.getCurrentHttpChannel().getRequest());
}
};
}
/**
* This gets called whenever a session is invalidated (because of user logout) or timed out.
* @param user - logged in UserIdentity
*/
@Override
public void logout(UserIdentity user) {
// no-op
if (logger.isTraceEnabled()) {
logger.trace("Web user {} logged out.", user.getUserPrincipal().getName());
}
}
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;
}
@Override
public UserIdentity login(final String username, final Object credentials, ServletRequest request) {
UserIdentity identity = null;
try {
identity = loggedInUgi.doAs((PrivilegedExceptionAction<UserIdentity>) () -> spnegoLogin(credentials));
} catch (Exception e) {
logger.error("Failed to login using SPNEGO", e);
}
return identity;
}
@Override
public UserIdentity getUserIdentity(HttpServletRequest request, String name) {
// ConfigurableSpnegoAuthenticator may pass names in servicename/host format but we only store the servicename
int nameHostSeparatorIndex = name.indexOf('/');
String serviceName = nameHostSeparatorIndex > 0 ? name.substring(0, nameHostSeparatorIndex) : name;
UserIdentity serviceIdentity = _adminUserStore.getUserIdentity(serviceName);
if (_trustedProxyIpPattern != null) {
return _trustedProxyIpPattern.matcher(request.getRemoteAddr()).matches() ? serviceIdentity : null;
} else {
return serviceIdentity;
}
}
@Override
public UserIdentity login(String username, Object credentials, ServletRequest request) {
if (!(request instanceof HttpServletRequest)) {
return null;
}
SpnegoUserIdentity serviceIdentity = (SpnegoUserIdentity) _delegateSpnegoLoginService.login(username, credentials, request);
SpnegoUserPrincipal servicePrincipal = (SpnegoUserPrincipal) serviceIdentity.getUserPrincipal();
String doAsUser = request.getParameter(DO_AS);
LOG.info("Authorizing proxy user {} from {} service", doAsUser, servicePrincipal.getName());
UserIdentity doAsIdentity = null;
if (doAsUser != null && !doAsUser.isEmpty()) {
doAsIdentity = _endUserAuthorizer.getUserIdentity((HttpServletRequest) request, doAsUser);
}
Principal principal = new TrustedProxyPrincipal(doAsUser, servicePrincipal);
Subject subject = new Subject(READ_ONLY_SUBJECT, Collections.singleton(principal), Collections.emptySet(), Collections.emptySet());
if (!serviceIdentity.isEstablished()) {
LOG.info("Service user {} isn't authorized as a trusted proxy", servicePrincipal.getName());
return new SpnegoUserIdentity(subject, principal, null);
} else {
if (doAsIdentity == null) {
LOG.info("Couldn't authorize user {}", doAsUser);
}
return new SpnegoUserIdentity(subject, principal, doAsIdentity);
}
}
public static UserIdentity createIdentity(SamlSession samlSession) {
Set<String> roles = samlSession.getRoles();
if (roles == null) {
roles = new HashSet<String>();
}
Subject theSubject = new Subject();
String[] theRoles = new String[roles.size()];
roles.toArray(theRoles);
return new DefaultUserIdentity(theSubject, samlSession.getPrincipal(), theRoles);
}
@Override
public Authentication createAuthentication(UserIdentity userIdentity, final Request request) {
return new KeycloakAuthentication(getAuthMethod(), userIdentity) {
@Override
public void logout() {
logoutCurrent(request);
}
};
}
@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;
}
}
private static UserIdentity getUserIdentity(SignedJWT jwtToken, JWTClaimsSet claimsSet, String serializedToken,
String username, UserIdentity rolesDelegate) {
JwtUserPrincipal principal = new JwtUserPrincipal(username, serializedToken);
Set<Object> privCreds = new HashSet<>();
privCreds.add(jwtToken);
privCreds.add(claimsSet);
Subject subject = new Subject(true, Collections.singleton(principal), Collections.emptySet(), privCreds);
return new JwtUserIdentity(subject, principal, rolesDelegate);
}
@Override
public UserIdentity getUserIdentity(HttpServletRequest request, String name) {
int hostSeparator = name.indexOf('/');
String shortName = hostSeparator > 0 ? name.substring(0, hostSeparator) : name;
int realmSeparator = shortName.indexOf('@');
shortName = realmSeparator > 0 ? shortName.substring(0, realmSeparator) : shortName;
return super.getUserIdentity(request, shortName);
}
@Override
protected Authentication createAuthentication(UserIdentity userIdentity, final Request request) {
return new KeycloakAuthentication(getAuthMethod(), userIdentity) {
@Override
public void logout() {
logoutCurrent(request);
}
};
}
@Test
public void testUnsuccessfulLoginWithIpFiltering() throws Exception {
TrustedProxyAuthorizationService srv = new TrustedProxyAuthorizationService(Collections.singletonList(AUTH_SERVICE_NAME), IP_FILTER);
HttpServletRequest mockRequest = mock(HttpServletRequest.class);
expect(mockRequest.getRemoteAddr()).andReturn("192.167.0.1");
replay(mockRequest);
srv.start();
try {
UserIdentity result = srv.getUserIdentity(mockRequest, AUTH_SERVICE_NAME);
assertNull(result);
} finally {
srv.stop();
}
}
@Test
public void testSuccessfulLoginWithoutIpFiltering() throws Exception {
TrustedProxyAuthorizationService srv = new TrustedProxyAuthorizationService(Collections.singletonList(AUTH_SERVICE_NAME), null);
HttpServletRequest mockRequest = mock(HttpServletRequest.class);
srv.start();
try {
UserIdentity result = srv.getUserIdentity(mockRequest, AUTH_SERVICE_NAME);
assertNotNull(result);
assertEquals(AUTH_SERVICE_NAME, result.getUserPrincipal().getName());
} finally {
srv.stop();
}
}
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;
}
@Override
protected Authentication createAuthentication(UserIdentity userIdentity, Request request) {
return new KeycloakAuthentication(getAuthMethod(), userIdentity) {
@Override
public void logout() {
logoutCurrent(HttpChannel.getCurrentHttpChannel().getRequest());
}
};
}
@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);
}