Search in sources :

Example 36 with AuthenticationResult

use of org.apache.qpid.server.security.auth.AuthenticationResult in project qpid-broker-j by apache.

the class OAuth2InteractiveAuthenticator method getAuthenticationHandler.

@Override
public AuthenticationHandler getAuthenticationHandler(final HttpServletRequest request, final HttpManagementConfiguration configuration) {
    final Port<?> port = configuration.getPort(request);
    if (configuration.getAuthenticationProvider(request) instanceof OAuth2AuthenticationProvider) {
        final OAuth2AuthenticationProvider oauth2Provider = (OAuth2AuthenticationProvider) configuration.getAuthenticationProvider(request);
        final Map<String, String> requestParameters;
        try {
            requestParameters = getRequestParameters(request);
        } catch (IllegalArgumentException e) {
            return new FailedAuthenticationHandler(400, "Some request parameters are included more than once " + request, e);
        }
        String error = requestParameters.get("error");
        if (error != null) {
            int responseCode = decodeErrorAsResponseCode(error);
            String errorDescription = requestParameters.get("error_description");
            if (responseCode == 403) {
                LOGGER.debug("Resource owner denies the access request");
                return new FailedAuthenticationHandler(responseCode, "Resource owner denies the access request");
            } else {
                LOGGER.warn("Authorization endpoint failed, error : '{}', error description '{}'", error, errorDescription);
                return new FailedAuthenticationHandler(responseCode, String.format("Authorization request failed :'%s'", error));
            }
        }
        final String authorizationCode = requestParameters.get("code");
        if (authorizationCode == null) {
            final String authorizationRedirectURL = buildAuthorizationRedirectURL(request, oauth2Provider);
            return response -> {
                final NamedAddressSpace addressSpace = configuration.getPort(request).getAddressSpace(request.getServerName());
                LOGGER.debug("Sending redirect to authorization endpoint {}", oauth2Provider.getAuthorizationEndpointURI(addressSpace));
                response.sendRedirect(authorizationRedirectURL);
            };
        } else {
            final HttpSession httpSession = request.getSession();
            String state = requestParameters.get("state");
            if (state == null) {
                LOGGER.warn("Deny login attempt with wrong state: {}", state);
                return new FailedAuthenticationHandler(400, "No state set on request with authorization code grant: " + request);
            }
            if (!checkState(request, state)) {
                LOGGER.warn("Deny login attempt with wrong state: {}", state);
                return new FailedAuthenticationHandler(401, "Received request with wrong state: " + state);
            }
            final String redirectUri = (String) httpSession.getAttribute(HttpManagementUtil.getRequestSpecificAttributeName(REDIRECT_URI_SESSION_ATTRIBUTE, request));
            final String originalRequestUri = (String) httpSession.getAttribute(HttpManagementUtil.getRequestSpecificAttributeName(ORIGINAL_REQUEST_URI_SESSION_ATTRIBUTE, request));
            final NamedAddressSpace addressSpace = configuration.getPort(request).getAddressSpace(request.getServerName());
            return new AuthenticationHandler() {

                @Override
                public void handleAuthentication(final HttpServletResponse response) throws IOException {
                    AuthenticationResult authenticationResult = oauth2Provider.authenticateViaAuthorizationCode(authorizationCode, redirectUri, addressSpace);
                    try {
                        Subject subject = createSubject(authenticationResult);
                        authoriseManagement(subject);
                        HttpManagementUtil.saveAuthorisedSubject(request, subject);
                        LOGGER.debug("Successful login. Redirect to original resource {}", originalRequestUri);
                        response.sendRedirect(originalRequestUri);
                    } catch (SecurityException e) {
                        if (e instanceof AccessControlException) {
                            LOGGER.info("User '{}' is not authorised for management", authenticationResult.getMainPrincipal());
                            response.sendError(403, "User is not authorised for management");
                        } else {
                            LOGGER.info("Authentication failed", authenticationResult.getCause());
                            response.sendError(401);
                        }
                    }
                }

                private Subject createSubject(final AuthenticationResult authenticationResult) {
                    SubjectCreator subjectCreator = port.getSubjectCreator(request.isSecure(), request.getServerName());
                    SubjectAuthenticationResult result = subjectCreator.createResultWithGroups(authenticationResult);
                    Subject original = result.getSubject();
                    if (original == null) {
                        throw new SecurityException("Only authenticated users can access the management interface");
                    }
                    Subject subject = HttpManagementUtil.createServletConnectionSubject(request, original);
                    return subject;
                }

                private void authoriseManagement(final Subject subject) {
                    Broker broker = (Broker) oauth2Provider.getParent();
                    HttpManagementUtil.assertManagementAccess(broker, subject);
                }
            };
        }
    } else {
        return null;
    }
}
Also used : HttpManagementUtil(org.apache.qpid.server.management.plugin.HttpManagementUtil) Enumeration(java.util.Enumeration) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) AuthenticationResult(org.apache.qpid.server.security.auth.AuthenticationResult) SecureRandom(java.security.SecureRandom) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpRequestInteractiveAuthenticator(org.apache.qpid.server.management.plugin.HttpRequestInteractiveAuthenticator) OAuth2Utils(org.apache.qpid.server.security.auth.manager.oauth2.OAuth2Utils) Map(java.util.Map) URI(java.net.URI) HttpSession(javax.servlet.http.HttpSession) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) Logger(org.slf4j.Logger) Port(org.apache.qpid.server.model.Port) OAuth2AuthenticationProvider(org.apache.qpid.server.security.auth.manager.oauth2.OAuth2AuthenticationProvider) Broker(org.apache.qpid.server.model.Broker) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) HttpManagementConfiguration(org.apache.qpid.server.management.plugin.HttpManagementConfiguration) Subject(javax.security.auth.Subject) SubjectCreator(org.apache.qpid.server.security.SubjectCreator) PluggableService(org.apache.qpid.server.plugin.PluggableService) NamedAddressSpace(org.apache.qpid.server.model.NamedAddressSpace) AccessControlException(java.security.AccessControlException) Collections(java.util.Collections) DatatypeConverter(javax.xml.bind.DatatypeConverter) Broker(org.apache.qpid.server.model.Broker) HttpSession(javax.servlet.http.HttpSession) NamedAddressSpace(org.apache.qpid.server.model.NamedAddressSpace) HttpServletResponse(javax.servlet.http.HttpServletResponse) AccessControlException(java.security.AccessControlException) Subject(javax.security.auth.Subject) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) AuthenticationResult(org.apache.qpid.server.security.auth.AuthenticationResult) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) OAuth2AuthenticationProvider(org.apache.qpid.server.security.auth.manager.oauth2.OAuth2AuthenticationProvider) SubjectCreator(org.apache.qpid.server.security.SubjectCreator)

Example 37 with AuthenticationResult

use of org.apache.qpid.server.security.auth.AuthenticationResult in project qpid-broker-j by apache.

the class OAuth2PreemptiveAuthenticator method attemptAuthentication.

@Override
public Subject attemptAuthentication(final HttpServletRequest request, final HttpManagementConfiguration configuration) {
    final Port<?> port = configuration.getPort(request);
    final AuthenticationProvider<?> authenticationProvider = configuration.getAuthenticationProvider(request);
    String authorizationHeader = request.getHeader("Authorization");
    String accessToken = null;
    if (authorizationHeader != null && authorizationHeader.startsWith(BEARER_PREFIX)) {
        accessToken = authorizationHeader.substring(BEARER_PREFIX.length());
    }
    if (accessToken != null && authenticationProvider instanceof OAuth2AuthenticationProvider) {
        OAuth2AuthenticationProvider<?> oAuth2AuthProvider = (OAuth2AuthenticationProvider<?>) authenticationProvider;
        AuthenticationResult authenticationResult = oAuth2AuthProvider.authenticateViaAccessToken(accessToken, null);
        SubjectCreator subjectCreator = port.getSubjectCreator(request.isSecure(), request.getServerName());
        SubjectAuthenticationResult result = subjectCreator.createResultWithGroups(authenticationResult);
        return result.getSubject();
    }
    return null;
}
Also used : OAuth2AuthenticationProvider(org.apache.qpid.server.security.auth.manager.oauth2.OAuth2AuthenticationProvider) SubjectCreator(org.apache.qpid.server.security.SubjectCreator) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) AuthenticationResult(org.apache.qpid.server.security.auth.AuthenticationResult)

Example 38 with AuthenticationResult

use of org.apache.qpid.server.security.auth.AuthenticationResult in project qpid-broker-j by apache.

the class OAuth2PreemptiveAuthenticatorTest method createMockOAuth2AuthenticationProvider.

private OAuth2AuthenticationProvider<?> createMockOAuth2AuthenticationProvider(final HttpPort mockPort) throws URISyntaxException {
    OAuth2AuthenticationProvider authenticationProvider = mock(OAuth2AuthenticationProvider.class);
    SubjectCreator mockSubjectCreator = mock(SubjectCreator.class);
    SubjectAuthenticationResult mockSuccessfulSubjectAuthenticationResult = mock(SubjectAuthenticationResult.class);
    SubjectAuthenticationResult mockUnauthorizedSubjectAuthenticationResult = mock(SubjectAuthenticationResult.class);
    final Subject successfulSubject = new Subject(true, Collections.singleton(new AuthenticatedPrincipal(new UsernamePrincipal(TEST_AUTHORIZED_USER, null))), Collections.emptySet(), Collections.emptySet());
    final Subject unauthorizedSubject = new Subject(true, Collections.singleton(new AuthenticatedPrincipal(new UsernamePrincipal(TEST_UNAUTHORIZED_USER, null))), Collections.emptySet(), Collections.emptySet());
    AuthenticationResult mockSuccessfulAuthenticationResult = mock(AuthenticationResult.class);
    AuthenticationResult mockUnauthorizedAuthenticationResult = mock(AuthenticationResult.class);
    AuthenticationResult failedAuthenticationResult = new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, new Exception("authentication failed"));
    SubjectAuthenticationResult failedSubjectAuthenticationResult = new SubjectAuthenticationResult(failedAuthenticationResult);
    when(mockPort.getSubjectCreator(any(Boolean.class), anyString())).thenReturn(mockSubjectCreator);
    when(authenticationProvider.authenticateViaAccessToken(TEST_VALID_ACCESS_TOKEN, null)).thenReturn(mockSuccessfulAuthenticationResult);
    when(authenticationProvider.authenticateViaAccessToken(TEST_INVALID_ACCESS_TOKEN, null)).thenReturn(failedAuthenticationResult);
    when(authenticationProvider.authenticateViaAccessToken(TEST_UNAUTHORIZED_ACCESS_TOKEN, null)).thenReturn(mockUnauthorizedAuthenticationResult);
    when(mockSuccessfulSubjectAuthenticationResult.getSubject()).thenReturn(successfulSubject);
    when(mockUnauthorizedSubjectAuthenticationResult.getSubject()).thenReturn(unauthorizedSubject);
    when(mockSubjectCreator.createResultWithGroups(mockSuccessfulAuthenticationResult)).thenReturn(mockSuccessfulSubjectAuthenticationResult);
    when(mockSubjectCreator.createResultWithGroups(mockUnauthorizedAuthenticationResult)).thenReturn(mockUnauthorizedSubjectAuthenticationResult);
    when(mockSubjectCreator.createResultWithGroups(failedAuthenticationResult)).thenReturn(failedSubjectAuthenticationResult);
    return authenticationProvider;
}
Also used : UsernamePrincipal(org.apache.qpid.server.security.auth.UsernamePrincipal) OAuth2AuthenticationProvider(org.apache.qpid.server.security.auth.manager.oauth2.OAuth2AuthenticationProvider) SubjectCreator(org.apache.qpid.server.security.SubjectCreator) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) Subject(javax.security.auth.Subject) URISyntaxException(java.net.URISyntaxException) AuthenticatedPrincipal(org.apache.qpid.server.security.auth.AuthenticatedPrincipal) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) AuthenticationResult(org.apache.qpid.server.security.auth.AuthenticationResult)

Example 39 with AuthenticationResult

use of org.apache.qpid.server.security.auth.AuthenticationResult in project qpid-broker-j by apache.

the class SubjectCreator method authenticate.

public SubjectAuthenticationResult authenticate(SaslNegotiator saslNegotiator, byte[] response) {
    AuthenticationResult authenticationResult = saslNegotiator.handleResponse(response);
    if (authenticationResult.getStatus() == AuthenticationStatus.SUCCESS) {
        return createResultWithGroups(authenticationResult);
    } else {
        if (authenticationResult.getStatus() == AuthenticationStatus.ERROR) {
            String authenticationId = saslNegotiator.getAttemptedAuthenticationId();
            _authenticationProvider.getEventLogger().message(AUTHENTICATION_FAILED(authenticationId, authenticationId != null));
        }
        return new SubjectAuthenticationResult(authenticationResult);
    }
}
Also used : SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) AuthenticationResult(org.apache.qpid.server.security.auth.AuthenticationResult)

Example 40 with AuthenticationResult

use of org.apache.qpid.server.security.auth.AuthenticationResult in project qpid-broker-j by apache.

the class AbstractScramAuthenticationManager method authenticate.

@Override
public AuthenticationResult authenticate(final String username, final String password) {
    ManagedUser user = getUser(username);
    if (user != null) {
        updateStoredPasswordFormatIfNecessary(user);
        SaltAndPasswordKeys saltAndPasswordKeys = getSaltAndPasswordKeys(username);
        try {
            byte[] saltedPassword = createSaltedPassword(saltAndPasswordKeys.getSalt(), password, saltAndPasswordKeys.getIterationCount());
            byte[] clientKey = computeHmac(saltedPassword, "Client Key");
            byte[] storedKey = MessageDigest.getInstance(getDigestName()).digest(clientKey);
            byte[] serverKey = computeHmac(saltedPassword, "Server Key");
            if (Arrays.equals(saltAndPasswordKeys.getStoredKey(), storedKey) && Arrays.equals(saltAndPasswordKeys.getServerKey(), serverKey)) {
                return new AuthenticationResult(new UsernamePrincipal(username, this));
            }
        } catch (IllegalArgumentException | NoSuchAlgorithmException | SaslException e) {
            return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
        }
    }
    return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR);
}
Also used : UsernamePrincipal(org.apache.qpid.server.security.auth.UsernamePrincipal) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SaslException(javax.security.sasl.SaslException) AuthenticationResult(org.apache.qpid.server.security.auth.AuthenticationResult)

Aggregations

AuthenticationResult (org.apache.qpid.server.security.auth.AuthenticationResult)78 UsernamePrincipal (org.apache.qpid.server.security.auth.UsernamePrincipal)13 SaslNegotiator (org.apache.qpid.server.security.auth.sasl.SaslNegotiator)13 X500Principal (javax.security.auth.x500.X500Principal)12 SubjectAuthenticationResult (org.apache.qpid.server.security.auth.SubjectAuthenticationResult)9 HashMap (java.util.HashMap)6 SubjectCreator (org.apache.qpid.server.security.SubjectCreator)6 Subject (javax.security.auth.Subject)5 IOException (java.io.IOException)4 OAuth2AuthenticationProvider (org.apache.qpid.server.security.auth.manager.oauth2.OAuth2AuthenticationProvider)4 InetSocketAddress (java.net.InetSocketAddress)3 URISyntaxException (java.net.URISyntaxException)3 Principal (java.security.Principal)3 Broker (org.apache.qpid.server.model.Broker)3 NamedAddressSpace (org.apache.qpid.server.model.NamedAddressSpace)3 AuthenticatedPrincipal (org.apache.qpid.server.security.auth.AuthenticatedPrincipal)3 URI (java.net.URI)2 AccessControlException (java.security.AccessControlException)2 EventLogger (org.apache.qpid.server.logging.EventLogger)2 User (org.apache.qpid.server.model.User)2