use of org.apache.qpid.server.security.auth.manager.oauth2.OAuth2AuthenticationProvider 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.manager.oauth2.OAuth2AuthenticationProvider in project qpid-broker-j by apache.
the class CloudFoundryOAuth2IdentityResolverService method getUserPrincipal.
@Override
public Principal getUserPrincipal(final OAuth2AuthenticationProvider<?> authenticationProvider, final String accessToken, final NamedAddressSpace addressSpace) throws IOException, IdentityResolverException {
URL checkTokenEndpoint = authenticationProvider.getIdentityResolverEndpointURI(addressSpace).toURL();
TrustStore trustStore = authenticationProvider.getTrustStore();
String clientId = authenticationProvider.getClientId();
String clientSecret = authenticationProvider.getClientSecret();
ConnectionBuilder connectionBuilder = new ConnectionBuilder(checkTokenEndpoint);
connectionBuilder.setConnectTimeout(authenticationProvider.getConnectTimeout()).setReadTimeout(authenticationProvider.getReadTimeout());
if (trustStore != null) {
try {
connectionBuilder.setTrustMangers(trustStore.getTrustManagers());
} catch (GeneralSecurityException e) {
throw new ServerScopedRuntimeException("Cannot initialise TLS", e);
}
}
connectionBuilder.setTlsProtocolWhiteList(authenticationProvider.getTlsProtocolWhiteList()).setTlsProtocolBlackList(authenticationProvider.getTlsProtocolBlackList()).setTlsCipherSuiteWhiteList(authenticationProvider.getTlsCipherSuiteWhiteList()).setTlsCipherSuiteBlackList(authenticationProvider.getTlsCipherSuiteBlackList());
LOGGER.debug("About to call identity service '{}'", checkTokenEndpoint);
HttpURLConnection 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");
String encoded = DatatypeConverter.printBase64Binary((clientId + ":" + clientSecret).getBytes(UTF_8));
connection.setRequestProperty("Authorization", "Basic " + encoded);
final Map<String, String> requestParameters = Collections.singletonMap("token", accessToken);
connection.connect();
try (OutputStream output = connection.getOutputStream()) {
output.write(OAuth2Utils.buildRequestQuery(requestParameters).getBytes(UTF_8));
output.close();
try (InputStream input = OAuth2Utils.getResponseStream(connection)) {
int responseCode = connection.getResponseCode();
LOGGER.debug("Call to identity service '{}' complete, response code : {}", checkTokenEndpoint, responseCode);
Map<String, String> responseMap = null;
try {
responseMap = _objectMapper.readValue(input, Map.class);
} catch (JsonProcessingException e) {
throw new IOException(String.format("Identity resolver '%s' did not return json", checkTokenEndpoint), e);
}
if (responseCode != 200) {
throw new IdentityResolverException(String.format("Identity resolver '%s' failed, response code %d, error '%s', description '%s'", checkTokenEndpoint, responseCode, responseMap.get("error"), responseMap.get("error_description")));
}
final String userName = responseMap.get("user_name");
if (userName == null) {
throw new IdentityResolverException(String.format("Identity resolver '%s' failed, response did not include 'user_name'", checkTokenEndpoint));
}
return new UsernamePrincipal(userName, authenticationProvider);
}
}
}
use of org.apache.qpid.server.security.auth.manager.oauth2.OAuth2AuthenticationProvider in project qpid-broker-j by apache.
the class GitHubOAuth2IdentityResolverService method getUserPrincipal.
@Override
public Principal getUserPrincipal(final OAuth2AuthenticationProvider<?> authenticationProvider, String accessToken, final NamedAddressSpace addressSpace) throws IOException, IdentityResolverException {
URL userInfoEndpoint = authenticationProvider.getIdentityResolverEndpointURI(addressSpace).toURL();
TrustStore trustStore = authenticationProvider.getTrustStore();
ConnectionBuilder connectionBuilder = new ConnectionBuilder(userInfoEndpoint);
connectionBuilder.setConnectTimeout(authenticationProvider.getConnectTimeout()).setReadTimeout(authenticationProvider.getReadTimeout());
if (trustStore != null) {
try {
connectionBuilder.setTrustMangers(trustStore.getTrustManagers());
} catch (GeneralSecurityException e) {
throw new ServerScopedRuntimeException("Cannot initialise TLS", e);
}
}
connectionBuilder.setTlsProtocolWhiteList(authenticationProvider.getTlsProtocolWhiteList()).setTlsProtocolBlackList(authenticationProvider.getTlsProtocolBlackList()).setTlsCipherSuiteWhiteList(authenticationProvider.getTlsCipherSuiteWhiteList()).setTlsCipherSuiteBlackList(authenticationProvider.getTlsCipherSuiteBlackList());
LOGGER.debug("About to call identity service '{}'", userInfoEndpoint);
HttpURLConnection connection = connectionBuilder.build();
connection.setRequestProperty("Accept-Charset", UTF8);
connection.setRequestProperty("Accept", "application/vnd.github.v3+json");
connection.setRequestProperty("Authorization", "token " + accessToken);
connection.connect();
try (InputStream input = OAuth2Utils.getResponseStream(connection)) {
int responseCode = connection.getResponseCode();
LOGGER.debug("Call to identity service '{}' complete, response code : {}", userInfoEndpoint, responseCode);
Map<String, String> responseMap;
try {
responseMap = _objectMapper.readValue(input, Map.class);
} catch (JsonProcessingException e) {
throw new IOException(String.format("Identity resolver '%s' did not return json", userInfoEndpoint), e);
}
if (responseCode != 200) {
throw new IdentityResolverException(String.format("Identity resolver '%s' failed, response code %d", userInfoEndpoint, responseCode));
}
final String githubId = responseMap.get("login");
if (githubId == null) {
throw new IdentityResolverException(String.format("Identity resolver '%s' failed, response did not include 'login'", userInfoEndpoint));
}
return new UsernamePrincipal(githubId, authenticationProvider);
}
}
use of org.apache.qpid.server.security.auth.manager.oauth2.OAuth2AuthenticationProvider in project qpid-broker-j by apache.
the class MicrosoftLiveOAuth2IdentityResolverService method getUserPrincipal.
@Override
public Principal getUserPrincipal(final OAuth2AuthenticationProvider<?> authenticationProvider, String accessToken, final NamedAddressSpace addressSpace) throws IOException, IdentityResolverException {
URL userInfoEndpoint = authenticationProvider.getIdentityResolverEndpointURI(addressSpace).toURL();
TrustStore trustStore = authenticationProvider.getTrustStore();
ConnectionBuilder connectionBuilder = new ConnectionBuilder(userInfoEndpoint);
connectionBuilder.setConnectTimeout(authenticationProvider.getConnectTimeout()).setReadTimeout(authenticationProvider.getReadTimeout());
if (trustStore != null) {
try {
connectionBuilder.setTrustMangers(trustStore.getTrustManagers());
} catch (GeneralSecurityException e) {
throw new ServerScopedRuntimeException("Cannot initialise TLS", e);
}
}
connectionBuilder.setTlsProtocolWhiteList(authenticationProvider.getTlsProtocolWhiteList()).setTlsProtocolBlackList(authenticationProvider.getTlsProtocolBlackList()).setTlsCipherSuiteWhiteList(authenticationProvider.getTlsCipherSuiteWhiteList()).setTlsCipherSuiteBlackList(authenticationProvider.getTlsCipherSuiteBlackList());
LOGGER.debug("About to call identity service '{}'", userInfoEndpoint);
HttpURLConnection connection = connectionBuilder.build();
connection.setRequestProperty("Accept-Charset", UTF8);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Authorization", "Bearer " + accessToken);
connection.connect();
try (InputStream input = OAuth2Utils.getResponseStream(connection)) {
int responseCode = connection.getResponseCode();
LOGGER.debug("Call to identity service '{}' complete, response code : {}", userInfoEndpoint, responseCode);
Map<String, String> responseMap;
try {
responseMap = _objectMapper.readValue(input, Map.class);
} catch (JsonProcessingException e) {
throw new IOException(String.format("Identity resolver '%s' did not return json", userInfoEndpoint), e);
}
if (responseCode != 200) {
throw new IdentityResolverException(String.format("Identity resolver '%s' failed, response code %d", userInfoEndpoint, responseCode));
}
final String liveId = responseMap.get("id");
if (liveId == null) {
throw new IdentityResolverException(String.format("Identity resolver '%s' failed, response did not include 'id'", userInfoEndpoint));
}
return new UsernamePrincipal(liveId, authenticationProvider);
}
}
use of org.apache.qpid.server.security.auth.manager.oauth2.OAuth2AuthenticationProvider 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;
}
}
Aggregations