use of io.undertow.security.idm.Account in project wildfly-swarm by wildfly-swarm.
the class JWTAuthMechanism method authenticate.
/**
* Extract the Authorization header and validate the bearer token if it exists. If it does, and is validated, this
* builds the org.jboss.security.SecurityContext authenticated Subject that drives the container APIs as well as
* the authorization layers.
*
* @param exchange - the http request exchange object
* @param securityContext - the current security context that
* @return one of AUTHENTICATED, NOT_AUTHENTICATED or NOT_ATTEMPTED depending on the header and authentication outcome.
*/
@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
List<String> authHeaders = exchange.getRequestHeaders().get(AUTHORIZATION);
if (authHeaders != null) {
String bearerToken = null;
for (String current : authHeaders) {
if (current.toLowerCase(Locale.ENGLISH).startsWith("bearer ")) {
bearerToken = current.substring(7);
if (UndertowLogger.SECURITY_LOGGER.isTraceEnabled()) {
UndertowLogger.SECURITY_LOGGER.tracef("Bearer token: %s", bearerToken);
}
try {
identityManager = securityContext.getIdentityManager();
JWTCredential credential = new JWTCredential(bearerToken, authContextInfo);
if (UndertowLogger.SECURITY_LOGGER.isTraceEnabled()) {
UndertowLogger.SECURITY_LOGGER.tracef("Bearer token: %s", bearerToken);
}
// Install the JWT principal as the caller
Account account = identityManager.verify(credential.getName(), credential);
if (account != null) {
JsonWebToken jwtPrincipal = (JsonWebToken) account.getPrincipal();
MPJWTProducer.setJWTPrincipal(jwtPrincipal);
JWTAccount jwtAccount = new JWTAccount(jwtPrincipal, account);
securityContext.authenticationComplete(jwtAccount, "MP-JWT", false);
// Workaround authenticated JsonWebToken not being installed as user principal
// https://issues.jboss.org/browse/WFLY-9212
org.jboss.security.SecurityContext jbSC = SecurityContextAssociation.getSecurityContext();
Subject subject = jbSC.getUtil().getSubject();
jbSC.getUtil().createSubjectInfo(jwtPrincipal, bearerToken, subject);
RoleGroup roles = extract(subject);
jbSC.getUtil().setRoles(roles);
UndertowLogger.SECURITY_LOGGER.debugf("Authenticated caller(%s) for path(%s) with roles: %s", credential.getName(), exchange.getRequestPath(), account.getRoles());
return AuthenticationMechanismOutcome.AUTHENTICATED;
} else {
UndertowLogger.SECURITY_LOGGER.info("Failed to authenticate JWT bearer token");
return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
}
} catch (Exception e) {
UndertowLogger.SECURITY_LOGGER.infof(e, "Failed to validate JWT bearer token");
return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
}
}
}
}
// No suitable header has been found in this request,
return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
use of io.undertow.security.idm.Account in project wildfly by wildfly.
the class DistributableSessionTestCase method setAuthenticatedSessionAttribute.
@Test
public void setAuthenticatedSessionAttribute() {
when(this.session.getMetaData()).thenReturn(this.metaData);
when(this.metaData.isNew()).thenReturn(false);
io.undertow.server.session.Session session = new DistributableSession(this.manager, this.session, this.config, this.batch, this.closeTask);
String name = CachedAuthenticatedSessionHandler.class.getName() + ".AuthenticatedSession";
Account account = mock(Account.class);
AuthenticatedSession auth = new AuthenticatedSession(account, HttpServletRequest.FORM_AUTH);
SessionManager<Map<String, Object>, Batch> manager = mock(SessionManager.class);
Batcher<Batch> batcher = mock(Batcher.class);
BatchContext context = mock(BatchContext.class);
SessionAttributes attributes = mock(SessionAttributes.class);
Account oldAccount = mock(Account.class);
AuthenticatedSession oldAuth = new AuthenticatedSession(oldAccount, HttpServletRequest.FORM_AUTH);
ArgumentCaptor<AuthenticatedSession> capturedAuth = ArgumentCaptor.forClass(AuthenticatedSession.class);
when(this.manager.getSessionManager()).thenReturn(manager);
when(manager.getBatcher()).thenReturn(batcher);
when(batcher.resumeBatch(this.batch)).thenReturn(context);
when(this.session.getAttributes()).thenReturn(attributes);
when(attributes.setAttribute(same(name), capturedAuth.capture())).thenReturn(oldAuth);
AuthenticatedSession result = (AuthenticatedSession) session.setAttribute(name, auth);
assertSame(auth.getAccount(), capturedAuth.getValue().getAccount());
assertSame(auth.getMechanism(), capturedAuth.getValue().getMechanism());
assertSame(oldAccount, result.getAccount());
assertSame(HttpServletRequest.FORM_AUTH, result.getMechanism());
verify(context).close();
verify(this.session, never()).close();
verify(this.closeTask, never()).accept(null);
reset(context, attributes);
capturedAuth = ArgumentCaptor.forClass(AuthenticatedSession.class);
when(attributes.setAttribute(same(name), capturedAuth.capture())).thenReturn(null);
result = (AuthenticatedSession) session.setAttribute(name, auth);
assertSame(auth.getAccount(), capturedAuth.getValue().getAccount());
assertSame(auth.getMechanism(), capturedAuth.getValue().getMechanism());
assertNull(result);
verify(context).close();
verify(this.session, never()).close();
verify(this.closeTask, never()).accept(null);
reset(context, attributes);
auth = new AuthenticatedSession(account, HttpServletRequest.BASIC_AUTH);
AuthenticatedSession oldSession = new AuthenticatedSession(oldAccount, HttpServletRequest.BASIC_AUTH);
Map<String, Object> localContext = new HashMap<>();
localContext.put(name, oldSession);
when(this.session.getLocalContext()).thenReturn(localContext);
result = (AuthenticatedSession) session.setAttribute(name, auth);
assertSame(auth, localContext.get(name));
verify(context).close();
verify(this.session, never()).close();
verify(this.closeTask, never()).accept(null);
reset(context);
doThrow(IllegalStateException.class).when(this.session).getAttributes();
assertThrows(IllegalStateException.class, () -> session.setAttribute(name, oldAuth));
verify(context).close();
verify(this.session).close();
verify(this.closeTask).accept(null);
}
use of io.undertow.security.idm.Account in project undertow by undertow-io.
the class BasicAuthenticationMechanism method authenticate.
/**
* @see io.undertow.server.HttpHandler#handleRequest(io.undertow.server.HttpServerExchange)
*/
@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
List<String> authHeaders = exchange.getRequestHeaders().get(AUTHORIZATION);
if (authHeaders != null) {
for (String current : authHeaders) {
if (current.toLowerCase(Locale.ENGLISH).startsWith(LOWERCASE_BASIC_PREFIX)) {
String base64Challenge = current.substring(PREFIX_LENGTH);
String plainChallenge = null;
try {
ByteBuffer decode = FlexBase64.decode(base64Challenge);
Charset charset = this.charset;
if (!userAgentCharsets.isEmpty()) {
String ua = exchange.getRequestHeaders().getFirst(Headers.USER_AGENT);
if (ua != null) {
for (Map.Entry<Pattern, Charset> entry : userAgentCharsets.entrySet()) {
if (entry.getKey().matcher(ua).find()) {
charset = entry.getValue();
break;
}
}
}
}
plainChallenge = new String(decode.array(), decode.arrayOffset(), decode.limit(), charset);
UndertowLogger.SECURITY_LOGGER.debugf("Found basic auth header (decoded using charset %s) in %s", charset, exchange);
} catch (IOException e) {
UndertowLogger.SECURITY_LOGGER.debugf(e, "Failed to decode basic auth header in %s", exchange);
}
int colonPos;
if (plainChallenge != null && (colonPos = plainChallenge.indexOf(COLON)) > -1) {
String userName = plainChallenge.substring(0, colonPos);
char[] password = plainChallenge.substring(colonPos + 1).toCharArray();
IdentityManager idm = getIdentityManager(securityContext);
PasswordCredential credential = new PasswordCredential(password);
try {
final AuthenticationMechanismOutcome result;
Account account = idm.verify(userName, credential);
if (account != null) {
securityContext.authenticationComplete(account, name, false);
result = AuthenticationMechanismOutcome.AUTHENTICATED;
} else {
securityContext.authenticationFailed(MESSAGES.authenticationFailed(userName), name);
result = AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
}
return result;
} finally {
clear(password);
}
}
// it was not correctly structured.
return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
}
}
}
// No suitable header has been found in this request,
return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
use of io.undertow.security.idm.Account in project undertow by undertow-io.
the class ClientCertAuthenticationMechanism method authenticate.
public AuthenticationMechanismOutcome authenticate(final HttpServerExchange exchange, final SecurityContext securityContext) {
SSLSessionInfo sslSession = exchange.getConnection().getSslSessionInfo();
if (sslSession != null) {
try {
Certificate[] clientCerts = getPeerCertificates(exchange, sslSession, securityContext);
if (clientCerts[0] instanceof X509Certificate) {
Credential credential = new X509CertificateCredential((X509Certificate) clientCerts[0]);
IdentityManager idm = getIdentityManager(securityContext);
Account account = idm.verify(credential);
if (account != null) {
securityContext.authenticationComplete(account, name, false);
return AuthenticationMechanismOutcome.AUTHENTICATED;
}
}
} catch (SSLPeerUnverifiedException e) {
// No action - this mechanism can not attempt authentication without peer certificates so allow it to drop out
// to NOT_ATTEMPTED.
}
}
return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
use of io.undertow.security.idm.Account in project undertow by undertow-io.
the class ExternalAuthenticationMechanism method authenticate.
@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
String principal = exchange.getAttachment(EXTERNAL_PRINCIPAL);
if (principal == null) {
return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
Account account = getIdentityManager(securityContext).verify(principal, ExternalCredential.INSTANCE);
if (account == null) {
return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
}
String name = exchange.getAttachment(EXTERNAL_AUTHENTICATION_TYPE);
securityContext.authenticationComplete(account, name != null ? name : this.name, false);
return AuthenticationMechanismOutcome.AUTHENTICATED;
}
Aggregations