Search in sources :

Example 1 with AuthenticationResult

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

the class OAuth2InteractiveAuthenticatorTest method createMockOAuth2AuthenticationProvider.

private OAuth2AuthenticationProvider<?> createMockOAuth2AuthenticationProvider(final HttpPort mockPort) throws URISyntaxException {
    OAuth2AuthenticationProvider authenticationProvider = mock(OAuth2AuthenticationProvider.class);
    Broker mockBroker = mock(Broker.class);
    SubjectCreator mockSubjectCreator = mock(SubjectCreator.class);
    when(_mockPort.getSubjectCreator(anyBoolean(), anyString())).thenReturn(mockSubjectCreator);
    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);
    doAnswer(new Answer() {

        @Override
        public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {
            final Subject subject = Subject.getSubject(AccessController.getContext());
            if (!subject.getPrincipals().iterator().next().getName().equals(TEST_AUTHORIZED_USER)) {
                throw new AccessControlException("access denied");
            }
            return null;
        }
    }).when(mockBroker).authorise(eq(Operation.PERFORM_ACTION("manage")));
    when(authenticationProvider.getAuthorizationEndpointURI(any())).thenReturn(new URI(TEST_AUTHORIZATION_ENDPOINT));
    when(authenticationProvider.getClientId()).thenReturn(TEST_CLIENT_ID);
    when(authenticationProvider.getScope()).thenReturn(TEST_OAUTH2_SCOPE);
    when(authenticationProvider.getParent()).thenReturn(mockBroker);
    when(authenticationProvider.authenticateViaAuthorizationCode(matches(TEST_VALID_AUTHORIZATION_CODE), matches(TEST_REQUEST_HOST), any())).thenReturn(mockSuccessfulAuthenticationResult);
    when(authenticationProvider.authenticateViaAuthorizationCode(matches(TEST_INVALID_AUTHORIZATION_CODE), matches(TEST_REQUEST_HOST), any())).thenReturn(failedAuthenticationResult);
    when(authenticationProvider.authenticateViaAuthorizationCode(matches(TEST_UNAUTHORIZED_AUTHORIZATION_CODE), matches(TEST_REQUEST_HOST), any())).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 : Broker(org.apache.qpid.server.model.Broker) AccessControlException(java.security.AccessControlException) HttpURI(org.eclipse.jetty.http.HttpURI) URI(java.net.URI) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) Subject(javax.security.auth.Subject) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) AccessControlException(java.security.AccessControlException) AuthenticatedPrincipal(org.apache.qpid.server.security.auth.AuthenticatedPrincipal) AuthenticationResult(org.apache.qpid.server.security.auth.AuthenticationResult) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) UsernamePrincipal(org.apache.qpid.server.security.auth.UsernamePrincipal) Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) OAuth2AuthenticationProvider(org.apache.qpid.server.security.auth.manager.oauth2.OAuth2AuthenticationProvider) SubjectCreator(org.apache.qpid.server.security.SubjectCreator)

Example 2 with AuthenticationResult

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

the class OAuth2AuthenticationProviderImpl method authenticateViaAuthorizationCode.

@Override
public AuthenticationResult authenticateViaAuthorizationCode(final String authorizationCode, final String redirectUri, NamedAddressSpace addressSpace) {
    URL tokenEndpoint;
    HttpURLConnection connection;
    byte[] body;
    try {
        tokenEndpoint = getTokenEndpointURI(addressSpace).toURL();
        ConnectionBuilder connectionBuilder = new ConnectionBuilder(tokenEndpoint);
        connectionBuilder.setConnectTimeout(_connectTimeout).setReadTimeout(_readTimeout);
        if (getTrustStore() != null) {
            try {
                connectionBuilder.setTrustMangers(getTrustStore().getTrustManagers());
            } catch (GeneralSecurityException e) {
                throw new ServerScopedRuntimeException("Cannot initialise TLS", e);
            }
        }
        connectionBuilder.setTlsProtocolWhiteList(getTlsProtocolWhiteList()).setTlsProtocolBlackList(getTlsProtocolBlackList()).setTlsCipherSuiteWhiteList(getTlsCipherSuiteWhiteList()).setTlsCipherSuiteBlackList(getTlsCipherSuiteBlackList());
        LOGGER.debug("About to call token endpoint '{}'", tokenEndpoint);
        connection = connectionBuilder.build();
        // makes sure to use POST
        connection.setDoOutput(true);
        connection.setRequestProperty("Accept-Charset", UTF_8.name());
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + UTF_8.name());
        connection.setRequestProperty("Accept", "application/json");
        if (getTokenEndpointNeedsAuth()) {
            String encoded = DatatypeConverter.printBase64Binary((getClientId() + ":" + getClientSecret()).getBytes(UTF_8));
            connection.setRequestProperty("Authorization", "Basic " + encoded);
        }
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("code", authorizationCode);
        requestBody.put("client_id", getClientId());
        requestBody.put("client_secret", getClientSecret());
        requestBody.put("redirect_uri", redirectUri);
        requestBody.put("grant_type", "authorization_code");
        requestBody.put("response_type", "token");
        body = OAuth2Utils.buildRequestQuery(requestBody).getBytes(UTF_8);
        connection.connect();
        try (OutputStream output = connection.getOutputStream()) {
            output.write(body);
        }
        try (InputStream input = OAuth2Utils.getResponseStream(connection)) {
            final int responseCode = connection.getResponseCode();
            LOGGER.debug("Call to token endpoint '{}' complete, response code : {}", tokenEndpoint, responseCode);
            Map<String, Object> responseMap = _objectMapper.readValue(input, Map.class);
            if (responseCode != 200 || responseMap.containsKey("error")) {
                IllegalStateException e = new IllegalStateException(String.format("Token endpoint failed, response code %d, error '%s', description '%s'", responseCode, responseMap.get("error"), responseMap.get("error_description")));
                LOGGER.error(e.getMessage());
                return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
            }
            Object accessTokenObject = responseMap.get("access_token");
            if (accessTokenObject == null) {
                IllegalStateException e = new IllegalStateException("Token endpoint response did not include 'access_token'");
                LOGGER.error("Unexpected token endpoint response", e);
                return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
            }
            String accessToken = String.valueOf(accessTokenObject);
            return authenticateViaAccessToken(accessToken, addressSpace);
        } catch (JsonProcessingException e) {
            IllegalStateException ise = new IllegalStateException(String.format("Token endpoint '%s' did not return json", tokenEndpoint), e);
            LOGGER.error("Unexpected token endpoint response", e);
            return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, ise);
        }
    } catch (IOException e) {
        LOGGER.error("Call to token endpoint failed", e);
        return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
    }
}
Also used : HashMap(java.util.HashMap) InputStream(java.io.InputStream) GeneralSecurityException(java.security.GeneralSecurityException) OutputStream(java.io.OutputStream) ConnectionBuilder(org.apache.qpid.server.util.ConnectionBuilder) IOException(java.io.IOException) URL(java.net.URL) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) AuthenticationResult(org.apache.qpid.server.security.auth.AuthenticationResult) HttpURLConnection(java.net.HttpURLConnection) ConfiguredObject(org.apache.qpid.server.model.ConfiguredObject) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 3 with AuthenticationResult

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

the class OAuth2Negotiator method handleResponse.

@Override
public AuthenticationResult handleResponse(final byte[] response) {
    if (_state == State.COMPLETE) {
        return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, new IllegalStateException("Multiple Authentications not permitted."));
    } else if (_state == State.INITIAL && (response == null || response.length == 0)) {
        _state = State.CHALLENGE_SENT;
        return new AuthenticationResult(new byte[0], AuthenticationResult.AuthenticationStatus.CONTINUE);
    }
    _state = State.COMPLETE;
    if (response == null || response.length == 0) {
        return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, new IllegalArgumentException("Invalid OAuth2 client response."));
    }
    Map<String, String> responsePairs = splitResponse(response);
    String auth = responsePairs.get("auth");
    if (auth != null) {
        if (auth.startsWith(BEARER_PREFIX)) {
            return _authenticationProvider.authenticateViaAccessToken(auth.substring(BEARER_PREFIX.length()), _addressSpace);
        } else {
            return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, new IllegalArgumentException("The 'auth' part of response does not not begin with the expected prefix"));
        }
    } else {
        return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, new IllegalArgumentException("The mandatory 'auth' part of the response was absent."));
    }
}
Also used : AuthenticationResult(org.apache.qpid.server.security.auth.AuthenticationResult)

Example 4 with AuthenticationResult

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

the class PlainNegotiator method handleResponse.

@Override
public AuthenticationResult handleResponse(final byte[] response) {
    if (_state == State.COMPLETE) {
        return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, new IllegalStateException("Multiple Authentications not permitted."));
    } else if (_state == State.INITIAL && (response == null || response.length == 0)) {
        _state = State.CHALLENGE_SENT;
        return new AuthenticationResult(new byte[0], AuthenticationResult.AuthenticationStatus.CONTINUE);
    }
    _state = State.COMPLETE;
    if (response == null || response.length == 0) {
        return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, new IllegalArgumentException("Invalid PLAIN encoding, authzid null terminator not found"));
    }
    int authzidNullPosition = findNullPosition(response, 0);
    if (authzidNullPosition < 0) {
        return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, new IllegalArgumentException("Invalid PLAIN encoding, authzid null terminator not found"));
    }
    int authcidNullPosition = findNullPosition(response, authzidNullPosition + 1);
    if (authcidNullPosition < 0) {
        return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, new IllegalArgumentException("Invalid PLAIN encoding, authcid null terminator not found"));
    }
    String password;
    _username = new String(response, authzidNullPosition + 1, authcidNullPosition - authzidNullPosition - 1, UTF8);
    // TODO: should not get pwd as a String but as a char array...
    int passwordLen = response.length - authcidNullPosition - 1;
    password = new String(response, authcidNullPosition + 1, passwordLen, UTF8);
    return _usernamePasswordAuthenticationProvider.authenticate(_username, password);
}
Also used : AuthenticationResult(org.apache.qpid.server.security.auth.AuthenticationResult)

Example 5 with AuthenticationResult

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

the class SubjectCreatorTest method testUnsuccessfulAuthentication.

private void testUnsuccessfulAuthentication(AuthenticationStatus expectedStatus) {
    AuthenticationResult failedAuthenticationResult = new AuthenticationResult(expectedStatus);
    when(_testSaslNegotiator.handleResponse(_saslResponseBytes)).thenReturn(failedAuthenticationResult);
    SubjectAuthenticationResult subjectAuthenticationResult = _subjectCreator.authenticate(_testSaslNegotiator, _saslResponseBytes);
    assertSame(expectedStatus, subjectAuthenticationResult.getStatus());
    assertNull(subjectAuthenticationResult.getSubject());
    if (expectedStatus == AuthenticationStatus.ERROR) {
        ArgumentCaptor<LogMessage> argument = ArgumentCaptor.forClass(LogMessage.class);
        verify(_eventLogger).message(argument.capture());
        assertTrue("Unexpected operational log message", argument.getValue().toString().startsWith("ATH-1010"));
    }
}
Also used : LogMessage(org.apache.qpid.server.logging.LogMessage) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) SubjectAuthenticationResult(org.apache.qpid.server.security.auth.SubjectAuthenticationResult) 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