Search in sources :

Example 1 with AuthenticationMethod

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);
    }
}
Also used : OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) Request(org.restlet.Request) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings) AuthenticationMethod(org.forgerock.oauth2.core.AuthenticationMethod) HashSet(java.util.HashSet)

Example 2 with AuthenticationMethod

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;
}
Also used : OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings) AuthenticationMethod(org.forgerock.oauth2.core.AuthenticationMethod)

Example 3 with AuthenticationMethod

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);
    }
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) HashMap(java.util.HashMap) SMSException(com.sun.identity.sm.SMSException) SSOException(com.iplanet.sso.SSOException) AuthenticationMethod(org.forgerock.oauth2.core.AuthenticationMethod) Map(java.util.Map) HashMap(java.util.HashMap)

Example 4 with AuthenticationMethod

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"));
}
Also used : ResourceOwnerAuthenticationRequired(org.forgerock.oauth2.core.exceptions.ResourceOwnerAuthenticationRequired) HashMap(java.util.HashMap) AuthenticationMethod(org.forgerock.oauth2.core.AuthenticationMethod) URI(java.net.URI) Test(org.testng.annotations.Test)

Example 5 with AuthenticationMethod

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
}
Also used : UnsupportedMediaTypeException(org.springframework.web.reactive.function.UnsupportedMediaTypeException) ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) WebClient(org.springframework.web.reactive.function.client.WebClient) HashSet(java.util.HashSet) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) Map(java.util.Map) UserInfoErrorResponse(com.nimbusds.openid.connect.sdk.UserInfoErrorResponse) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) ClientResponse(org.springframework.web.reactive.function.client.ClientResponse) HttpHeaders(org.springframework.http.HttpHeaders) OAuth2UserAuthority(org.springframework.security.oauth2.core.user.OAuth2UserAuthority) MediaType(org.springframework.http.MediaType) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) Set(java.util.Set) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) Mono(reactor.core.publisher.Mono) GrantedAuthority(org.springframework.security.core.GrantedAuthority) HttpStatus(org.springframework.http.HttpStatus) AuthenticationMethod(org.springframework.security.oauth2.core.AuthenticationMethod) JSONObject(net.minidev.json.JSONObject) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) AuthenticationMethod(org.springframework.security.oauth2.core.AuthenticationMethod) OAuth2UserAuthority(org.springframework.security.oauth2.core.user.OAuth2UserAuthority) WebClient(org.springframework.web.reactive.function.client.WebClient) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UnsupportedMediaTypeException(org.springframework.web.reactive.function.UnsupportedMediaTypeException) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) Map(java.util.Map) HashSet(java.util.HashSet)

Aggregations

AuthenticationMethod (org.forgerock.oauth2.core.AuthenticationMethod)4 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 Map (java.util.Map)2 OAuth2ProviderSettings (org.forgerock.oauth2.core.OAuth2ProviderSettings)2 SSOException (com.iplanet.sso.SSOException)1 ErrorObject (com.nimbusds.oauth2.sdk.ErrorObject)1 UserInfoErrorResponse (com.nimbusds.openid.connect.sdk.UserInfoErrorResponse)1 SMSException (com.sun.identity.sm.SMSException)1 URI (java.net.URI)1 Set (java.util.Set)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 JSONObject (net.minidev.json.JSONObject)1 OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)1 ResourceOwnerAuthenticationRequired (org.forgerock.oauth2.core.exceptions.ResourceOwnerAuthenticationRequired)1 ServerException (org.forgerock.oauth2.core.exceptions.ServerException)1 Request (org.restlet.Request)1 ParameterizedTypeReference (org.springframework.core.ParameterizedTypeReference)1 HttpHeaders (org.springframework.http.HttpHeaders)1 HttpStatus (org.springframework.http.HttpStatus)1