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;
}
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);
}
}
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."));
}
}
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);
}
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"));
}
}
Aggregations