Java Code Examples for io.undertow.security.idm.IdentityManager#verify()

The following examples show how to use io.undertow.security.idm.IdentityManager#verify() . 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: 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 2
Source File: ClientCertAuthenticationMechanism.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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.
        }
    }

    /*
     * 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 3
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 4
Source File: GSSAPIAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
public AuthenticationMechanismOutcome run() throws GSSException {
    NegotiationContext negContext = exchange.getAttachment(NegotiationContext.ATTACHMENT_KEY);
    if (negContext == null) {
        negContext = new NegotiationContext();
        exchange.putAttachment(NegotiationContext.ATTACHMENT_KEY, negContext);
    }

    GSSContext gssContext = negContext.getGssContext();
    if (gssContext == null) {
        GSSManager manager = GSSManager.getInstance();

        GSSCredential credential = manager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, mechanisms, GSSCredential.ACCEPT_ONLY);

        gssContext = manager.createContext(credential);

        negContext.setGssContext(gssContext);
    }

    byte[] respToken = gssContext.acceptSecContext(challenge.array(), challenge.arrayOffset(), challenge.writerIndex());
    negContext.setResponseToken(respToken);

    if (negContext.isEstablished()) {

        if (respToken != null) {
            // There will be no further challenge but we do have a token so set it here.
            exchange.addResponseHeader(WWW_AUTHENTICATE,
                    NEGOTIATE_PREFIX + FlexBase64.encodeString(respToken, false));
        }
        IdentityManager identityManager = securityContext.getIdentityManager();
        final Account account = identityManager.verify(new GSSContextCredential(negContext.getGssContext()));
        if (account != null) {
            securityContext.authenticationComplete(account, name, false);
            return AuthenticationMechanismOutcome.AUTHENTICATED;
        } else {
            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }
    } else {
        // This isn't a failure but as the context is not established another round trip with the client is needed.
        return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
    }
}
 
Example 5
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 6
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 7
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 8
Source File: GSSAPIAuthenticationMechanism.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public AuthenticationMechanismOutcome run() throws GSSException {
    NegotiationContext negContext = exchange.getAttachment(NegotiationContext.ATTACHMENT_KEY);
    if (negContext == null) {
        negContext = new NegotiationContext();
        exchange.putAttachment(NegotiationContext.ATTACHMENT_KEY, negContext);
        // Also cache it on the connection for future calls.
        exchange.getConnection().putAttachment(NegotiationContext.ATTACHMENT_KEY, negContext);
    }

    GSSContext gssContext = negContext.getGssContext();
    if (gssContext == null) {
        GSSManager manager = GSSManager.getInstance();

        GSSCredential credential = manager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, mechanisms, GSSCredential.ACCEPT_ONLY);

        gssContext = manager.createContext(credential);

        negContext.setGssContext(gssContext);
    }

    byte[] respToken = gssContext.acceptSecContext(challenge.array(), challenge.arrayOffset(), challenge.limit());
    negContext.setResponseToken(respToken);

    if (negContext.isEstablished()) {

        if (respToken != null) {
            // There will be no further challenge but we do have a token so set it here.
            exchange.getResponseHeaders().add(WWW_AUTHENTICATE,
                    NEGOTIATE_PREFIX + FlexBase64.encodeString(respToken, false));
        }
        IdentityManager identityManager = securityContext.getIdentityManager();
        final Account account = identityManager.verify(new GSSContextCredential(negContext.getGssContext()));
        if (account != null) {
            securityContext.authenticationComplete(account, name, false);
            return AuthenticationMechanismOutcome.AUTHENTICATED;
        } else {
            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }
    } else {
        // This isn't a failure but as the context is not established another round trip with the client is needed.
        return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
    }
}
 
Example 9
Source File: FormAuthenticationMechanism.java    From lams with GNU General Public License v2.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();
        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 10
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 11
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;
}
 
Example 12
Source File: LightGSSAPIAuthenticationMechanism.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
@Override
public AuthenticationMechanismOutcome run() throws GSSException {
    NegotiationContext negContext = exchange.getAttachment(NegotiationContext.ATTACHMENT_KEY);
    if (negContext == null) {
        negContext = new NegotiationContext();
        exchange.putAttachment(NegotiationContext.ATTACHMENT_KEY, negContext);
        // Also cache it on the connection for future calls.
        exchange.getConnection().putAttachment(NegotiationContext.ATTACHMENT_KEY, negContext);
    }

    GSSContext gssContext = negContext.getGssContext();
    if (gssContext == null) {
        GSSManager manager = GSSManager.getInstance();

        GSSCredential credential = manager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, mechanisms, GSSCredential.ACCEPT_ONLY);

        gssContext = manager.createContext(credential);

        negContext.setGssContext(gssContext);
    }

    byte[] respToken = gssContext.acceptSecContext(challenge.array(), challenge.arrayOffset(), challenge.limit());
    negContext.setResponseToken(respToken);

    if (negContext.isEstablished()) {

        if (respToken != null) {
            // There will be no further challenge but we do have a token so set it here.
            exchange.getResponseHeaders().add(WWW_AUTHENTICATE,
                    NEGOTIATE_PREFIX + FlexBase64.encodeString(respToken, false));
        }
        IdentityManager identityManager = securityContext.getIdentityManager();
        // 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);
            return AuthenticationMechanismOutcome.AUTHENTICATED;
        } else {
            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }
    } else {
        // This isn't a failure but as the context is not established another round trip with the client is needed.
        return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
    }
}
 
Example 13
Source File: LightFormAuthenticationMechanism.java    From light-oauth2 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();
            final FormData.FormValue jUsername = data.getFirst("j_username");
            final FormData.FormValue jPassword = data.getFirst("j_password");
            final FormData.FormValue jClientId = data.getFirst("client_id");
            final FormData.FormValue jUserType = data.getFirst("user_type");
            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();
            final String userType = jUserType.getValue();
            final String clientId = jClientId.getValue();

            // get clientAuthClass and userType
            String clientAuthClass = null;
            IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
            Client client = clients.get(clientId);
            if(client != null) {
                clientAuthClass = client.getAuthenticateClass();
            }

            AuthenticationMechanismOutcome outcome = null;
            LightPasswordCredential credential = new LightPasswordCredential(password.toCharArray(), clientAuthClass, userType, exchange);
            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 14
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;
}