Java Code Examples for io.undertow.security.api.SecurityContext#authenticationComplete()

The following examples show how to use io.undertow.security.api.SecurityContext#authenticationComplete() . 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: CachedAuthenticatedSessionMechanism.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
public AuthenticationMechanismOutcome runCached(final HttpServerExchange exchange, final SecurityContext securityContext, final AuthenticatedSessionManager sessionManager) {
    AuthenticatedSession authSession = sessionManager.lookupSession(exchange);
    if (authSession != null) {
        Account account = getIdentityManager(securityContext).verify(authSession.getAccount());
        if (account != null) {
            securityContext.authenticationComplete(account, authSession.getMechanism(), false);
            return AuthenticationMechanismOutcome.AUTHENTICATED;
        } else {
            sessionManager.clearSession(exchange);
            // We know we had a previously authenticated account but for some reason the IdentityManager is no longer
            // accepting it, we now
            return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
        }
    } else {
        // It is possible an AuthenticatedSessionManager could have been available even if there was no chance of it
        // loading a session.
        return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
    }

}
 
Example 2
Source File: GenericHeaderAuthenticationMechanism.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
    String principal = getPrincipal(exchange);
    if(principal == null) {
        return NOT_ATTEMPTED;
    }
    String session = getSession(exchange);
    if(session == null) {
        return NOT_ATTEMPTED;
    }
    Account account = identityManager.verify(principal, new PasswordCredential(session.toCharArray()));
    if(account == null) {
        securityContext.authenticationFailed(UndertowMessages.MESSAGES.authenticationFailed(principal), mechanismName);
        return NOT_AUTHENTICATED;
    }
    securityContext.authenticationComplete(account, mechanismName, false);
    return AUTHENTICATED;
}
 
Example 3
Source File: CachedAuthenticatedSessionMechanism.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public AuthenticationMechanismOutcome runCached(final HttpServerExchange exchange, final SecurityContext securityContext, final AuthenticatedSessionManager sessionManager) {
    AuthenticatedSession authSession = sessionManager.lookupSession(exchange);
    if (authSession != null) {
        Account account = getIdentityManager(securityContext).verify(authSession.getAccount());
        if (account != null) {
            securityContext.authenticationComplete(account, authSession.getMechanism(), false);
            return AuthenticationMechanismOutcome.AUTHENTICATED;
        } else {
            sessionManager.clearSession(exchange);
            // We know we had a previously authenticated account but for some reason the IdentityManager is no longer
            // accepting it, we now
            return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
        }
    } else {
        // It is possible an AuthenticatedSessionManager could have been available even if there was no chance of it
        // loading a session.
        return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
    }

}
 
Example 4
Source File: GenericHeaderAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
    String principal = getPrincipal(exchange);
    if (principal == null) {
        return NOT_ATTEMPTED;
    }
    String session = getSession(exchange);
    if (session == null) {
        return NOT_ATTEMPTED;
    }
    Account account = identityManager.verify(principal, new PasswordCredential(session.toCharArray()));
    if (account == null) {
        securityContext.authenticationFailed(UndertowMessages.MESSAGES.authenticationFailed(principal), mechanismName);
        return NOT_AUTHENTICATED;
    }
    securityContext.authenticationComplete(account, mechanismName, false);
    return AUTHENTICATED;
}
 
Example 5
Source File: QuarkusAuthMechanism.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
    VertxHttpExchange delegate = (VertxHttpExchange) exchange.getDelegate();
    RoutingContext context = (RoutingContext) delegate.getContext();
    try {
        SecurityIdentity identity = QuarkusHttpUser.getSecurityIdentityBlocking(context, null);
        if (identity != null && !identity.isAnonymous()) {
            //associate the identity
            securityContext.authenticationComplete(new QuarkusUndertowAccount(identity), "Quarkus",
                    false);
            return AuthenticationMechanismOutcome.AUTHENTICATED;
        }
        return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
    } catch (AuthenticationFailedException e) {
        return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
    }
}
 
Example 6
Source File: ExternalAuthenticationMechanism.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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;
}
 
Example 7
Source File: AnonymousMechanism.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext context) {
    Principal user = new RealmUser(ANONYMOUS_USER);
    Subject subject = new Subject();
    subject.getPrincipals().add(user);
    SocketAddress address = exchange.getConnection().getPeerAddress();
    if (address instanceof InetSocketAddress) {
        subject.getPrincipals().add(new InetAddressPrincipal(((InetSocketAddress) address).getAddress()));
    }

    context.authenticationComplete(new RealmIdentityAccount(subject, user), ANONYMOUS_MECH, false);

    return AuthenticationMechanismOutcome.AUTHENTICATED;
}
 
Example 8
Source File: JWTAuthMechanism.java    From thorntail with Apache License 2.0 5 votes vote down vote up
/**
 * 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.
 */
@SuppressWarnings("deprecation")
@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
    String jwtToken = new UndertowBearerTokenExtractor(authContextInfo, exchange).getBearerToken();
    if (jwtToken != null) {
        try {
            identityManager = securityContext.getIdentityManager();
            JWTCredential credential = new JWTCredential(jwtToken, authContextInfo);
            // Install the JWT principal as the caller
            Account account = identityManager.verify(credential.getName(), credential);
            if (account != null) {
                JsonWebToken jwtPrincipal = (JsonWebToken) account.getPrincipal();
                preparePrincipalProducer(jwtPrincipal);
                securityContext.authenticationComplete(account, "MP-JWT", false);
                // Workaround authenticated JWTPrincipal 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, jwtToken, 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;
}
 
Example 9
Source File: SingleSignOnAuthenticationMechanism.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
    Cookie cookie = exchange.getRequestCookies().get(cookieName);
    if (cookie != null) {
        final String ssoId = cookie.getValue();
        log.tracef("Found SSO cookie %s", ssoId);
        try (SingleSignOn sso = this.singleSignOnManager.findSingleSignOn(ssoId)) {
            if (sso != null) {
                if(log.isTraceEnabled()) {
                    log.tracef("SSO session with ID: %s found.", ssoId);
                }
                Account verified = getIdentityManager(securityContext).verify(sso.getAccount());
                if (verified == null) {
                    if(log.isTraceEnabled()) {
                        log.tracef("Account not found. Returning 'not attempted' here.");
                    }
                    //we return not attempted here to allow other mechanisms to proceed as normal
                    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
                }
                final Session session = getSession(exchange);
                registerSessionIfRequired(sso, session);
                securityContext.authenticationComplete(verified, sso.getMechanismName(), false);
                securityContext.registerNotificationReceiver(new NotificationReceiver() {
                    @Override
                    public void handleNotification(SecurityNotification notification) {
                        if (notification.getEventType() == SecurityNotification.EventType.LOGGED_OUT) {
                            singleSignOnManager.removeSingleSignOn(sso);
                        }
                    }
                });
                log.tracef("Authenticated account %s using SSO", verified.getPrincipal().getName());
                return AuthenticationMechanismOutcome.AUTHENTICATED;
            }
        }
        clearSsoCookie(exchange);
    }
    exchange.addResponseWrapper(responseListener);
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
 
Example 10
Source File: ExternalAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 11
Source File: DatawaveAuthenticationMechanism.java    From datawave with Apache License 2.0 5 votes vote down vote up
private AuthenticationMechanismOutcome authenticated(HttpServerExchange exchange, SecurityContext securityContext, Account account) {
    if (exchange.getRequestHeaders().contains(HEADER_PROXIED_ENTITIES)) {
        exchange.getResponseHeaders().add(HEADER_PROXIED_ENTITIES_ACCEPTED, "true");
    }
    
    securityContext.authenticationComplete(account, name, false);
    addTimingRequestHeaders(exchange);
    return AuthenticationMechanismOutcome.AUTHENTICATED;
}
 
Example 12
Source File: ClientCertAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public AuthenticationMechanismOutcome authenticate(final HttpServerExchange exchange, final SecurityContext securityContext) {
    SSLSessionInfo sslSession = exchange.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.
        }
    }

    /*
     * For ClientCert we do not have a concept of a failed authentication, if the client did use a key then it was deemed
     * acceptable for the connection to be established, this mechanism then just 'attempts' to use it for authentication but
     * does not mandate success.
     */

    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
 
Example 13
Source File: SingleSignOnAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
    Cookie cookie = exchange.getRequestCookies().get(cookieName);
    if (cookie != null) {
        final String ssoId = cookie.getValue();
        log.tracef("Found SSO cookie %s", ssoId);
        try (SingleSignOn sso = this.singleSignOnManager.findSingleSignOn(ssoId)) {
            if (sso != null) {
                if (log.isTraceEnabled()) {
                    log.tracef("SSO session with ID: %s found.", ssoId);
                }
                Account verified = getIdentityManager(securityContext).verify(sso.getAccount());
                if (verified == null) {
                    if (log.isTraceEnabled()) {
                        log.tracef("Account not found. Returning 'not attempted' here.");
                    }
                    //we return not attempted here to allow other mechanisms to proceed as normal
                    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
                }
                final Session session = getSession(exchange);
                registerSessionIfRequired(sso, session);
                securityContext.authenticationComplete(verified, sso.getMechanismName(), false);
                securityContext.registerNotificationReceiver(new NotificationReceiver() {
                    @Override
                    public void handleNotification(SecurityNotification notification) {
                        if (notification.getEventType() == SecurityNotification.EventType.LOGGED_OUT) {
                            singleSignOnManager.removeSingleSignOn(sso);
                        }
                    }
                });
                log.tracef("Authenticated account %s using SSO", verified.getPrincipal().getName());
                return AuthenticationMechanismOutcome.AUTHENTICATED;
            }
        }
        clearSsoCookie(exchange);
    }
    exchange.addResponseCommitListener(responseListener);
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
 
Example 14
Source File: BasicAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
/**
 * @see io.undertow.server.HttpHandler#handleRequest(io.undertow.server.HttpServerExchange)
 */
@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {

    List<String> authHeaders = exchange.getRequestHeaders(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 {
                    ByteBuf decode = FlexBase64.decode(base64Challenge);

                    Charset charset = this.charset;
                    if(!userAgentCharsets.isEmpty()) {
                        String ua = exchange.getRequestHeader(HttpHeaderNames.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.writerIndex(), charset);
                    UndertowLogger.SECURITY_LOGGER.debugf("Found basic auth header %s (decoded using charset %s) in %s", plainChallenge, charset, exchange);
                } catch (IOException e) {
                    UndertowLogger.SECURITY_LOGGER.debugf(e, "Failed to decode basic auth header %s in %s", base64Challenge, 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);
                    }
                }

                // By this point we had a header we should have been able to verify but for some reason
                // it was not correctly structured.
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
        }
    }

    // No suitable header has been found in this request,
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
 
Example 15
Source File: GSSAPIAuthenticationMechanism.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public AuthenticationMechanismOutcome authenticate(final HttpServerExchange exchange,
                                                   final SecurityContext securityContext) {
    ServerConnection connection = exchange.getConnection();
    NegotiationContext negContext = connection.getAttachment(NegotiationContext.ATTACHMENT_KEY);
    if (negContext != null) {

        UndertowLogger.SECURITY_LOGGER.debugf("Existing negotiation context found for %s", exchange);
        exchange.putAttachment(NegotiationContext.ATTACHMENT_KEY, negContext);
        if (negContext.isEstablished()) {
            IdentityManager identityManager = getIdentityManager(securityContext);
            final Account account = identityManager.verify(new GSSContextCredential(negContext.getGssContext()));
            if (account != null) {
                securityContext.authenticationComplete(account, name, false);
                UndertowLogger.SECURITY_LOGGER.debugf("Authenticated as user %s with existing GSSAPI negotiation context for %s", account.getPrincipal().getName(), exchange);
                return AuthenticationMechanismOutcome.AUTHENTICATED;
            } else {
                UndertowLogger.SECURITY_LOGGER.debugf("Failed to authenticate with existing GSSAPI negotiation context for %s", exchange);
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
        }
    }

    List<String> authHeaders = exchange.getRequestHeaders().get(AUTHORIZATION);
    if (authHeaders != null) {
        for (String current : authHeaders) {
            if (current.startsWith(NEGOTIATE_PREFIX)) {
                String base64Challenge = current.substring(NEGOTIATE_PREFIX.length());
                try {
                    ByteBuffer challenge = FlexBase64.decode(base64Challenge);
                    return runGSSAPI(exchange, challenge, securityContext);
                } catch (IOException e) {
                }

                // By this point we had a header we should have been able to verify but for some reason
                // it was not correctly structured.
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
        }
    }

    // No suitable header was found so authentication was not even attempted.
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
 
Example 16
Source File: FormAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
public AuthenticationMechanismOutcome runFormAuth(final HttpServerExchange exchange, final SecurityContext securityContext) {
    final FormDataParser parser = formParserFactory.createParser(exchange);
    if (parser == null) {
        UndertowLogger.SECURITY_LOGGER.debug("Could not authenticate as no form parser is present");
        // TODO - May need a better error signaling mechanism here to prevent repeated attempts.
        return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
    }

    try {
        final FormData data = parser.parseBlocking();
        if (data == null) {
            UndertowLogger.SECURITY_LOGGER.debug("Could not authenticate as no form parser is present");
            // TODO - May need a better error signaling mechanism here to prevent repeated attempts.
            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }

        final FormData.FormValue jUsername = data.getFirst("j_username");
        final FormData.FormValue jPassword = data.getFirst("j_password");
        if (jUsername == null || jPassword == null) {
            UndertowLogger.SECURITY_LOGGER.debugf("Could not authenticate as username or password was not present in the posted result for %s", exchange);
            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }
        final String userName = jUsername.getValue();
        final String password = jPassword.getValue();
        AuthenticationMechanismOutcome outcome = null;
        PasswordCredential credential = new PasswordCredential(password.toCharArray());
        try {
            IdentityManager identityManager = getIdentityManager(securityContext);
            Account account = identityManager.verify(userName, credential);
            if (account != null) {
                securityContext.authenticationComplete(account, name, true);
                UndertowLogger.SECURITY_LOGGER.debugf("Authenticated user %s using for auth for %s", account.getPrincipal().getName(), exchange);
                outcome = AuthenticationMechanismOutcome.AUTHENTICATED;
            } else {
                securityContext.authenticationFailed(MESSAGES.authenticationFailed(userName), name);
            }
        } finally {
            if (outcome == AuthenticationMechanismOutcome.AUTHENTICATED) {
                handleRedirectBack(exchange);
                exchange.endExchange();
            }
            return outcome != null ? outcome : AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 17
Source File: BasicAuthenticationMechanism.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @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 %s (decoded using charset %s) in %s", plainChallenge, charset, exchange);
                } catch (IOException e) {
                    UndertowLogger.SECURITY_LOGGER.debugf(e, "Failed to decode basic auth header %s in %s", base64Challenge, 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);
                    }
                }

                // By this point we had a header we should have been able to verify but for some reason
                // it was not correctly structured.
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
        }
    }

    // No suitable header has been found in this request,
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
 
Example 18
Source File: GSSAPIAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@Override
public AuthenticationMechanismOutcome authenticate(final HttpServerExchange exchange,
                                                   final SecurityContext securityContext) {
    NegotiationContext negContext = exchange.getAttachment(NegotiationContext.ATTACHMENT_KEY);
    if (negContext != null) {

        UndertowLogger.SECURITY_LOGGER.debugf("Existing negotiation context found for %s", exchange);
        exchange.putAttachment(NegotiationContext.ATTACHMENT_KEY, negContext);
        if (negContext.isEstablished()) {
            IdentityManager identityManager = getIdentityManager(securityContext);
            final Account account = identityManager.verify(new GSSContextCredential(negContext.getGssContext()));
            if (account != null) {
                securityContext.authenticationComplete(account, name, false);
                UndertowLogger.SECURITY_LOGGER.debugf("Authenticated as user %s with existing GSSAPI negotiation context for %s", account.getPrincipal().getName(), exchange);
                return AuthenticationMechanismOutcome.AUTHENTICATED;
            } else {
                UndertowLogger.SECURITY_LOGGER.debugf("Failed to authenticate with existing GSSAPI negotiation context for %s", exchange);
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
        }
    }

    List<String> authHeaders = exchange.getRequestHeaders(AUTHORIZATION);
    if (authHeaders != null) {
        for (String current : authHeaders) {
            if (current.startsWith(NEGOTIATE_PREFIX)) {
                String base64Challenge = current.substring(NEGOTIATE_PREFIX.length());
                try {
                    ByteBuf challenge = FlexBase64.decode(base64Challenge);
                    return runGSSAPI(exchange, challenge, securityContext);
                } catch (IOException e) {
                }

                // By this point we had a header we should have been able to verify but for some reason
                // it was not correctly structured.
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
        }
    }

    // No suitable header was found so authentication was not even attempted.
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
 
Example 19
Source File: LightBasicAuthenticationMechanism.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
/**
 * @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);
                    if(logger.isDebugEnabled()) logger.debug("Found basic auth header %s (decoded using charset %s) in %s", plainChallenge, charset, exchange);
                } catch (IOException e) {
                    logger.error("Failed to decode basic auth header " + base64Challenge + " in " + exchange, e);
                }
                int colonPos;
                if (plainChallenge != null && (colonPos = plainChallenge.indexOf(COLON)) > -1) {
                    String userName = plainChallenge.substring(0, colonPos);
                    char[] password = plainChallenge.substring(colonPos + 1).toCharArray();

                    // get clientAuthClass and userType
                    String clientAuthClass = null;
                    String userType = null;
                    Map<String, Deque<String>> params = exchange.getQueryParameters();
                    Deque<String> clientIdDeque = params.get("client_id");
                    if(clientIdDeque != null) {
                        String clientId = clientIdDeque.getFirst();
                        IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
                        Client client = clients.get(clientId);
                        if(client != null) {
                            clientAuthClass = client.getAuthenticateClass();
                        }
                    }
                    Deque<String> userTypeDeque = params.get("user_type");
                    if(userTypeDeque != null) {
                        userType = userTypeDeque.getFirst();
                    }

                    IdentityManager idm = getIdentityManager(securityContext);
                    LightPasswordCredential credential = new LightPasswordCredential(password, clientAuthClass, userType, exchange);
                    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);
                    }
                }

                // By this point we had a header we should have been able to verify but for some reason
                // it was not correctly structured.
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
        }
    }

    // No suitable header has been found in this request,
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
 
Example 20
Source File: LightGSSAPIAuthenticationMechanism.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
@Override
public AuthenticationMechanismOutcome authenticate(final HttpServerExchange exchange,
                                                   final SecurityContext securityContext) {
    ServerConnection connection = exchange.getConnection();
    NegotiationContext negContext = connection.getAttachment(NegotiationContext.ATTACHMENT_KEY);
    if (negContext != null) {

        if(logger.isDebugEnabled()) logger.debug("Existing negotiation context found for %s", exchange);
        exchange.putAttachment(NegotiationContext.ATTACHMENT_KEY, negContext);
        if (negContext.isEstablished()) {
            IdentityManager identityManager = getIdentityManager(securityContext);
            // get the client authenticate class and user type from the exchange.
            String clientAuthClass = null;
            String userType = null;
            Map<String, Deque<String>> params = exchange.getQueryParameters();
            Deque<String> clientIdDeque = params.get("client_id");
            if(clientIdDeque != null) {
                String clientId = clientIdDeque.getFirst();
                IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
                Client client = clients.get(clientId);
                if(client != null) {
                    clientAuthClass = client.getAuthenticateClass();
                }
            }
            Deque<String> userTypeDeque = params.get("user_type");
            if(userTypeDeque != null) {
                userType = userTypeDeque.getFirst();
            }

            final Account account = identityManager.verify(new LightGSSContextCredential(negContext.getGssContext(), clientAuthClass, userType));
            if (account != null) {
                securityContext.authenticationComplete(account, name, false);
                if(logger.isDebugEnabled()) logger.debug("Authenticated as user %s with existing GSSAPI negotiation context for %s", account.getPrincipal().getName(), exchange);
                return AuthenticationMechanismOutcome.AUTHENTICATED;
            } else {
                if(logger.isDebugEnabled()) logger.debug("Failed to authenticate with existing GSSAPI negotiation context for %s", exchange);
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
        }
    }

    List<String> authHeaders = exchange.getRequestHeaders().get(AUTHORIZATION);
    if (authHeaders != null) {
        for (String current : authHeaders) {
            if (current.startsWith(NEGOTIATE_PREFIX)) {
                String base64Challenge = current.substring(NEGOTIATE_PREFIX.length());
                try {
                    ByteBuffer challenge = FlexBase64.decode(base64Challenge);
                    return runGSSAPI(exchange, challenge, securityContext);
                } catch (IOException e) {
                }

                // By this point we had a header we should have been able to verify but for some reason
                // it was not correctly structured.
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
        }
    }

    // No suitable header was found so authentication was not even attempted.
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}