Search in sources :

Example 6 with Scope

use of com.nimbusds.oauth2.sdk.Scope in project iaf by ibissource.

the class OAuthAccessTokenManager method createRequest.

private TokenRequest createRequest(Credentials credentials) throws HttpAuthenticationException {
    AuthorizationGrant grant;
    if (useClientCredentialsGrant) {
        grant = new ClientCredentialsGrant();
    } else {
        String username = credentials.getUserPrincipal().getName();
        Secret password = new Secret(credentials.getPassword());
        grant = new ResourceOwnerPasswordCredentialsGrant(username, password);
    }
    // The credentials to authenticate the client at the token endpoint
    ClientID clientID = new ClientID(client_cf.getUsername());
    Secret clientSecret = new Secret(client_cf.getPassword());
    ClientAuthentication clientAuth = new ClientSecretBasic(clientID, clientSecret);
    try {
        URI _tokenEndpoint = new URI(tokenEndpoint);
        return new TokenRequest(_tokenEndpoint, clientAuth, grant, scope);
    } catch (URISyntaxException e) {
        throw new HttpAuthenticationException("illegal token endpoint", e);
    }
}
Also used : Secret(com.nimbusds.oauth2.sdk.auth.Secret) ClientCredentialsGrant(com.nimbusds.oauth2.sdk.ClientCredentialsGrant) TokenRequest(com.nimbusds.oauth2.sdk.TokenRequest) ResourceOwnerPasswordCredentialsGrant(com.nimbusds.oauth2.sdk.ResourceOwnerPasswordCredentialsGrant) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) URISyntaxException(java.net.URISyntaxException) AuthorizationGrant(com.nimbusds.oauth2.sdk.AuthorizationGrant) ClientAuthentication(com.nimbusds.oauth2.sdk.auth.ClientAuthentication) URI(java.net.URI) ClientSecretBasic(com.nimbusds.oauth2.sdk.auth.ClientSecretBasic)

Example 7 with Scope

use of com.nimbusds.oauth2.sdk.Scope in project iaf by ibissource.

the class OAuthAccessTokenManagerTest method scopeTest.

@Test
public void scopeTest() {
    Scope scope1 = new Scope("read", "write");
    Scope scope2 = Scope.parse("read write");
    Scope scope3 = Scope.parse("read, write");
    assertEquals("read write", scope1.toString());
    assertEquals("read write", scope2.toString());
    assertEquals("read write", scope3.toString());
}
Also used : Scope(com.nimbusds.oauth2.sdk.Scope) Test(org.junit.Test)

Example 8 with Scope

use of com.nimbusds.oauth2.sdk.Scope 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)

Example 9 with Scope

use of com.nimbusds.oauth2.sdk.Scope in project spring-security by spring-projects.

the class NimbusAuthorizationCodeTokenResponseClient method getTokenResponse.

@Override
public OAuth2AccessTokenResponse getTokenResponse(OAuth2AuthorizationCodeGrantRequest authorizationGrantRequest) {
    ClientRegistration clientRegistration = authorizationGrantRequest.getClientRegistration();
    // Build the authorization code grant request for the token endpoint
    AuthorizationCode authorizationCode = new AuthorizationCode(authorizationGrantRequest.getAuthorizationExchange().getAuthorizationResponse().getCode());
    URI redirectUri = toURI(authorizationGrantRequest.getAuthorizationExchange().getAuthorizationRequest().getRedirectUri());
    AuthorizationGrant authorizationCodeGrant = new AuthorizationCodeGrant(authorizationCode, redirectUri);
    URI tokenUri = toURI(clientRegistration.getProviderDetails().getTokenUri());
    // Set the credentials to authenticate the client at the token endpoint
    ClientID clientId = new ClientID(clientRegistration.getClientId());
    Secret clientSecret = new Secret(clientRegistration.getClientSecret());
    boolean isPost = ClientAuthenticationMethod.CLIENT_SECRET_POST.equals(clientRegistration.getClientAuthenticationMethod()) || ClientAuthenticationMethod.POST.equals(clientRegistration.getClientAuthenticationMethod());
    ClientAuthentication clientAuthentication = isPost ? new ClientSecretPost(clientId, clientSecret) : new ClientSecretBasic(clientId, clientSecret);
    com.nimbusds.oauth2.sdk.TokenResponse tokenResponse = getTokenResponse(authorizationCodeGrant, tokenUri, clientAuthentication);
    if (!tokenResponse.indicatesSuccess()) {
        TokenErrorResponse tokenErrorResponse = (TokenErrorResponse) tokenResponse;
        ErrorObject errorObject = tokenErrorResponse.getErrorObject();
        throw new OAuth2AuthorizationException(getOAuthError(errorObject));
    }
    AccessTokenResponse accessTokenResponse = (AccessTokenResponse) tokenResponse;
    String accessToken = accessTokenResponse.getTokens().getAccessToken().getValue();
    OAuth2AccessToken.TokenType accessTokenType = null;
    if (OAuth2AccessToken.TokenType.BEARER.getValue().equalsIgnoreCase(accessTokenResponse.getTokens().getAccessToken().getType().getValue())) {
        accessTokenType = OAuth2AccessToken.TokenType.BEARER;
    }
    long expiresIn = accessTokenResponse.getTokens().getAccessToken().getLifetime();
    // As per spec, in section 5.1 Successful Access Token Response
    // https://tools.ietf.org/html/rfc6749#section-5.1
    // If AccessTokenResponse.scope is empty, then default to the scope
    // originally requested by the client in the Authorization Request
    Set<String> scopes = getScopes(authorizationGrantRequest, accessTokenResponse);
    String refreshToken = null;
    if (accessTokenResponse.getTokens().getRefreshToken() != null) {
        refreshToken = accessTokenResponse.getTokens().getRefreshToken().getValue();
    }
    Map<String, Object> additionalParameters = new LinkedHashMap<>(accessTokenResponse.getCustomParameters());
    // @formatter:off
    return OAuth2AccessTokenResponse.withToken(accessToken).tokenType(accessTokenType).expiresIn(expiresIn).scopes(scopes).refreshToken(refreshToken).additionalParameters(additionalParameters).build();
// @formatter:on
}
Also used : URI(java.net.URI) ClientSecretBasic(com.nimbusds.oauth2.sdk.auth.ClientSecretBasic) LinkedHashMap(java.util.LinkedHashMap) TokenErrorResponse(com.nimbusds.oauth2.sdk.TokenErrorResponse) ClientSecretPost(com.nimbusds.oauth2.sdk.auth.ClientSecretPost) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) AuthorizationGrant(com.nimbusds.oauth2.sdk.AuthorizationGrant) ClientAuthentication(com.nimbusds.oauth2.sdk.auth.ClientAuthentication) AccessTokenResponse(com.nimbusds.oauth2.sdk.AccessTokenResponse) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) Secret(com.nimbusds.oauth2.sdk.auth.Secret) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) AuthorizationCodeGrant(com.nimbusds.oauth2.sdk.AuthorizationCodeGrant) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject)

Example 10 with Scope

use of com.nimbusds.oauth2.sdk.Scope in project spring-security by spring-projects.

the class NimbusReactiveOpaqueTokenIntrospector method convertClaimsSet.

private OAuth2AuthenticatedPrincipal convertClaimsSet(TokenIntrospectionSuccessResponse response) {
    Map<String, Object> claims = response.toJSONObject();
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    if (response.getAudience() != null) {
        List<String> audiences = new ArrayList<>();
        for (Audience audience : response.getAudience()) {
            audiences.add(audience.getValue());
        }
        claims.put(OAuth2TokenIntrospectionClaimNames.AUD, Collections.unmodifiableList(audiences));
    }
    if (response.getClientID() != null) {
        claims.put(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, response.getClientID().getValue());
    }
    if (response.getExpirationTime() != null) {
        Instant exp = response.getExpirationTime().toInstant();
        claims.put(OAuth2TokenIntrospectionClaimNames.EXP, exp);
    }
    if (response.getIssueTime() != null) {
        Instant iat = response.getIssueTime().toInstant();
        claims.put(OAuth2TokenIntrospectionClaimNames.IAT, iat);
    }
    if (response.getIssuer() != null) {
        // RFC-7662 page 7 directs users to RFC-7519 for defining the values of these
        // issuer fields.
        // https://datatracker.ietf.org/doc/html/rfc7662#page-7
        // 
        // RFC-7519 page 9 defines issuer fields as being 'case-sensitive' strings
        // containing
        // a 'StringOrURI', which is defined on page 5 as being any string, but
        // strings containing ':'
        // should be treated as valid URIs.
        // https://datatracker.ietf.org/doc/html/rfc7519#section-2
        // 
        // It is not defined however as to whether-or-not normalized URIs should be
        // treated as the same literal
        // value. It only defines validation itself, so to avoid potential ambiguity
        // or unwanted side effects that
        // may be awkward to debug, we do not want to manipulate this value. Previous
        // versions of Spring Security
        // would *only* allow valid URLs, which is not what we wish to achieve here.
        claims.put(OAuth2TokenIntrospectionClaimNames.ISS, response.getIssuer().getValue());
    }
    if (response.getNotBeforeTime() != null) {
        claims.put(OAuth2TokenIntrospectionClaimNames.NBF, response.getNotBeforeTime().toInstant());
    }
    if (response.getScope() != null) {
        List<String> scopes = Collections.unmodifiableList(response.getScope().toStringList());
        claims.put(OAuth2TokenIntrospectionClaimNames.SCOPE, scopes);
        for (String scope : scopes) {
            authorities.add(new SimpleGrantedAuthority(AUTHORITY_PREFIX + scope));
        }
    }
    return new OAuth2IntrospectionAuthenticatedPrincipal(claims, authorities);
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) Audience(com.nimbusds.oauth2.sdk.id.Audience) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Instant(java.time.Instant) ArrayList(java.util.ArrayList) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject)

Aggregations

ErrorObject (com.nimbusds.oauth2.sdk.ErrorObject)4 URI (java.net.URI)3 GrantedAuthority (org.springframework.security.core.GrantedAuthority)3 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)3 AuthorizationGrant (com.nimbusds.oauth2.sdk.AuthorizationGrant)2 Scope (com.nimbusds.oauth2.sdk.Scope)2 ClientAuthentication (com.nimbusds.oauth2.sdk.auth.ClientAuthentication)2 ClientSecretBasic (com.nimbusds.oauth2.sdk.auth.ClientSecretBasic)2 Secret (com.nimbusds.oauth2.sdk.auth.Secret)2 Audience (com.nimbusds.oauth2.sdk.id.Audience)2 ClientID (com.nimbusds.oauth2.sdk.id.ClientID)2 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)2 Instant (java.time.Instant)2 ArrayList (java.util.ArrayList)2 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)2 JWT (com.nimbusds.jwt.JWT)1 SignedJWT (com.nimbusds.jwt.SignedJWT)1 AccessTokenResponse (com.nimbusds.oauth2.sdk.AccessTokenResponse)1 AuthorizationCode (com.nimbusds.oauth2.sdk.AuthorizationCode)1 AuthorizationCodeGrant (com.nimbusds.oauth2.sdk.AuthorizationCodeGrant)1