use of org.springframework.security.oauth2.core.AuthenticationMethod in project OpenAM by OpenRock.
the class OpenAMResourceOwnerSessionValidator method setCurrentAcr.
/**
* If the user is already logged in when the OAuth2 request comes in with an acr_values parameter, we
* look to see if they've already matched one. If they have, we set the acr value on the request.
*/
private void setCurrentAcr(SSOToken token, OAuth2Request request, String acrValuesStr) throws NotFoundException, ServerException, SSOException, AccessDeniedException, UnsupportedEncodingException, URISyntaxException, ResourceOwnerAuthenticationRequired {
String serviceUsed = token.getProperty(ISAuthConstants.SERVICE);
Set<String> acrValues = new HashSet<>(Arrays.asList(acrValuesStr.split("\\s+")));
OAuth2ProviderSettings settings = providerSettingsFactory.get(request);
Map<String, AuthenticationMethod> acrMap = settings.getAcrMapping();
boolean matched = false;
for (String acr : acrValues) {
if (acrMap.containsKey(acr)) {
if (serviceUsed.equals(acrMap.get(acr).getName())) {
final Request req = request.getRequest();
req.getResourceRef().addQueryParameter(OAuth2Constants.JWTTokenParams.ACR, acr);
matched = true;
}
}
}
if (!matched) {
throw authenticationRequired(request, token);
}
}
use of org.springframework.security.oauth2.core.AuthenticationMethod in project OpenAM by OpenRock.
the class OpenAMResourceOwnerSessionValidator method chooseBestAcrValue.
/**
* Searches through the supplied 'acr' values to find a matching authentication context configuration service for
* this OpenID Connect client. If the client is not an OIDC client, or if no match is found, then {@code null} is
* returned and the default login configuration for the realm will be used. Values will be tried in the order
* passed, and the first matching value will be chosen.
*
* @param request the OAuth2 request that requires authentication.
* @param acrValues the values of the acr_values parameter, in preference order.
* @return the matching ACR value, or {@code null} if no match was found.
*/
private ACRValue chooseBestAcrValue(final OAuth2Request request, final String... acrValues) throws ServerException, NotFoundException {
final OAuth2ProviderSettings settings = providerSettingsFactory.get(request);
final Map<String, AuthenticationMethod> mapping = settings.getAcrMapping();
if (mapping != null) {
for (String acrValue : acrValues) {
final AuthenticationMethod method = mapping.get(acrValue);
if (method instanceof OpenAMAuthenticationMethod) {
if (logger.messageEnabled()) {
logger.message("Picked ACR value [" + acrValue + "] -> " + method);
}
return new ACRValue(acrValue, (OpenAMAuthenticationMethod) method);
}
}
}
if (logger.messageEnabled()) {
logger.message("No ACR value matched - using default login configuration");
}
return null;
}
use of org.springframework.security.oauth2.core.AuthenticationMethod in project OpenAM by OpenRock.
the class OpenAMOAuth2ProviderSettings method getAcrMapping.
@Override
public Map<String, AuthenticationMethod> getAcrMapping() throws ServerException {
try {
final Map<String, String> map = getMapSetting(realm, OAuth2ProviderService.ACR_VALUE_MAPPING);
final Map<String, AuthenticationMethod> methods = new HashMap<String, AuthenticationMethod>(map.size());
for (Map.Entry<String, String> entry : map.entrySet()) {
methods.put(entry.getKey(), new OpenAMAuthenticationMethod(entry.getValue(), AuthContext.IndexType.SERVICE));
}
return methods;
} catch (SSOException e) {
logger.message(e.getMessage());
throw new ServerException(e);
} catch (SMSException e) {
logger.message(e.getMessage());
throw new ServerException(e);
}
}
use of org.springframework.security.oauth2.core.AuthenticationMethod in project OpenAM by OpenRock.
the class OpenAMResourceOwnerSessionValidatorTest method shouldUseFirstAcrValueThatIsSupported.
@Test
public void shouldUseFirstAcrValueThatIsSupported() throws Exception {
// Given
String acrValues = "1 2 3";
mockPrompt("login");
mockSSOToken(NO_SESSION_TOKEN);
mockRequestAcrValues(acrValues);
final Map<String, AuthenticationMethod> acrMap = new HashMap<>();
acrMap.put("2", new OpenAMAuthenticationMethod("service2", AuthContext.IndexType.SERVICE));
acrMap.put("3", new OpenAMAuthenticationMethod("service3", AuthContext.IndexType.SERVICE));
mockAcrValuesMap(acrMap);
// When
URI loginUri = null;
try {
resourceOwnerSessionValidator.validate(mockOAuth2Request);
fail();
} catch (ResourceOwnerAuthenticationRequired ex) {
loginUri = ex.getRedirectUri();
}
// Then
assertTrue(loginUri.getQuery().contains("service=service2"));
}
use of org.springframework.security.oauth2.core.AuthenticationMethod in project spring-security by spring-projects.
the class DefaultReactiveOAuth2UserService method loadUser.
@Override
public Mono<OAuth2User> loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
return Mono.defer(() -> {
Assert.notNull(userRequest, "userRequest cannot be null");
String userInfoUri = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri();
if (!StringUtils.hasText(userInfoUri)) {
OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_INFO_URI_ERROR_CODE, "Missing required UserInfo Uri in UserInfoEndpoint for Client Registration: " + userRequest.getClientRegistration().getRegistrationId(), null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName();
if (!StringUtils.hasText(userNameAttributeName)) {
OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_NAME_ATTRIBUTE_ERROR_CODE, "Missing required \"user name\" attribute name in UserInfoEndpoint for Client Registration: " + userRequest.getClientRegistration().getRegistrationId(), null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
AuthenticationMethod authenticationMethod = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getAuthenticationMethod();
WebClient.RequestHeadersSpec<?> requestHeadersSpec = getRequestHeaderSpec(userRequest, userInfoUri, authenticationMethod);
// @formatter:off
Mono<Map<String, Object>> userAttributes = requestHeadersSpec.retrieve().onStatus(HttpStatus::isError, (response) -> parse(response).map((userInfoErrorResponse) -> {
String description = userInfoErrorResponse.getErrorObject().getDescription();
OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, description, null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
})).bodyToMono(DefaultReactiveOAuth2UserService.STRING_OBJECT_MAP);
return userAttributes.map((attrs) -> {
GrantedAuthority authority = new OAuth2UserAuthority(attrs);
Set<GrantedAuthority> authorities = new HashSet<>();
authorities.add(authority);
OAuth2AccessToken token = userRequest.getAccessToken();
for (String scope : token.getScopes()) {
authorities.add(new SimpleGrantedAuthority("SCOPE_" + scope));
}
return new DefaultOAuth2User(authorities, attrs, userNameAttributeName);
}).onErrorMap((ex) -> (ex instanceof UnsupportedMediaTypeException || ex.getCause() instanceof UnsupportedMediaTypeException), (ex) -> {
String contentType = (ex instanceof UnsupportedMediaTypeException) ? ((UnsupportedMediaTypeException) ex).getContentType().toString() : ((UnsupportedMediaTypeException) ex.getCause()).getContentType().toString();
String errorMessage = "An error occurred while attempting to retrieve the UserInfo Resource from '" + userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri() + "': response contains invalid content type '" + contentType + "'. " + "The UserInfo Response should return a JSON object (content type 'application/json') " + "that contains a collection of name and value pairs of the claims about the authenticated End-User. " + "Please ensure the UserInfo Uri in UserInfoEndpoint for Client Registration '" + userRequest.getClientRegistration().getRegistrationId() + "' conforms to the UserInfo Endpoint, " + "as defined in OpenID Connect 1.0: 'https://openid.net/specs/openid-connect-core-1_0.html#UserInfo'";
OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, errorMessage, null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
}).onErrorMap((ex) -> {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, "An error occurred reading the UserInfo response: " + ex.getMessage(), null);
return new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
});
});
// @formatter:on
}
Aggregations