Search in sources :

Example 1 with ClaimAccessor

use of org.springframework.security.oauth2.core.ClaimAccessor in project spring-authorization-server by spring-projects.

the class OAuth2RefreshTokenAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    OAuth2RefreshTokenAuthenticationToken refreshTokenAuthentication = (OAuth2RefreshTokenAuthenticationToken) authentication;
    OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(refreshTokenAuthentication);
    RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
    OAuth2Authorization authorization = this.authorizationService.findByToken(refreshTokenAuthentication.getRefreshToken(), OAuth2TokenType.REFRESH_TOKEN);
    if (authorization == null) {
        throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);
    }
    if (!registeredClient.getId().equals(authorization.getRegisteredClientId())) {
        throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT);
    }
    if (!registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.REFRESH_TOKEN)) {
        throw new OAuth2AuthenticationException(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT);
    }
    OAuth2Authorization.Token<OAuth2RefreshToken> refreshToken = authorization.getRefreshToken();
    if (!refreshToken.isActive()) {
        // resource owner credentials) or refresh token is invalid, expired, revoked [...].
        throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);
    }
    // As per https://tools.ietf.org/html/rfc6749#section-6
    // The requested scope MUST NOT include any scope not originally granted by the resource owner,
    // and if omitted is treated as equal to the scope originally granted by the resource owner.
    Set<String> scopes = refreshTokenAuthentication.getScopes();
    Set<String> authorizedScopes = authorization.getAttribute(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME);
    if (!authorizedScopes.containsAll(scopes)) {
        throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_SCOPE);
    }
    if (scopes.isEmpty()) {
        scopes = authorizedScopes;
    }
    // @formatter:off
    DefaultOAuth2TokenContext.Builder tokenContextBuilder = DefaultOAuth2TokenContext.builder().registeredClient(registeredClient).principal(authorization.getAttribute(Principal.class.getName())).providerContext(ProviderContextHolder.getProviderContext()).authorization(authorization).authorizedScopes(scopes).authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN).authorizationGrant(refreshTokenAuthentication);
    // @formatter:on
    OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization.from(authorization);
    // ----- Access token -----
    OAuth2TokenContext tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.ACCESS_TOKEN).build();
    OAuth2Token generatedAccessToken = this.tokenGenerator.generate(tokenContext);
    if (generatedAccessToken == null) {
        OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, "The token generator failed to generate the access token.", ERROR_URI);
        throw new OAuth2AuthenticationException(error);
    }
    OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, generatedAccessToken.getTokenValue(), generatedAccessToken.getIssuedAt(), generatedAccessToken.getExpiresAt(), tokenContext.getAuthorizedScopes());
    if (generatedAccessToken instanceof ClaimAccessor) {
        authorizationBuilder.token(accessToken, (metadata) -> {
            metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, ((ClaimAccessor) generatedAccessToken).getClaims());
            metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, false);
        });
    } else {
        authorizationBuilder.accessToken(accessToken);
    }
    // ----- Refresh token -----
    OAuth2RefreshToken currentRefreshToken = refreshToken.getToken();
    if (!registeredClient.getTokenSettings().isReuseRefreshTokens()) {
        if (this.refreshTokenGenerator != null) {
            Instant issuedAt = Instant.now();
            Instant expiresAt = issuedAt.plus(registeredClient.getTokenSettings().getRefreshTokenTimeToLive());
            currentRefreshToken = new OAuth2RefreshToken(this.refreshTokenGenerator.get(), issuedAt, expiresAt);
        } else {
            tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.REFRESH_TOKEN).build();
            OAuth2Token generatedRefreshToken = this.tokenGenerator.generate(tokenContext);
            if (!(generatedRefreshToken instanceof OAuth2RefreshToken)) {
                OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, "The token generator failed to generate the refresh token.", ERROR_URI);
                throw new OAuth2AuthenticationException(error);
            }
            currentRefreshToken = (OAuth2RefreshToken) generatedRefreshToken;
        }
        authorizationBuilder.refreshToken(currentRefreshToken);
    }
    // ----- ID token -----
    OidcIdToken idToken;
    if (authorizedScopes.contains(OidcScopes.OPENID)) {
        tokenContext = tokenContextBuilder.tokenType(ID_TOKEN_TOKEN_TYPE).build();
        OAuth2Token generatedIdToken = this.tokenGenerator.generate(tokenContext);
        if (!(generatedIdToken instanceof Jwt)) {
            OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, "The token generator failed to generate the ID token.", ERROR_URI);
            throw new OAuth2AuthenticationException(error);
        }
        idToken = new OidcIdToken(generatedIdToken.getTokenValue(), generatedIdToken.getIssuedAt(), generatedIdToken.getExpiresAt(), ((Jwt) generatedIdToken).getClaims());
        authorizationBuilder.token(idToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims()));
    } else {
        idToken = null;
    }
    authorization = authorizationBuilder.build();
    this.authorizationService.save(authorization);
    Map<String, Object> additionalParameters = Collections.emptyMap();
    if (idToken != null) {
        additionalParameters = new HashMap<>();
        additionalParameters.put(OidcParameterNames.ID_TOKEN, idToken.getTokenValue());
    }
    return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, accessToken, currentRefreshToken, additionalParameters);
}
Also used : OidcIdToken(org.springframework.security.oauth2.core.oidc.OidcIdToken) OAuth2Token(org.springframework.security.oauth2.core.OAuth2Token) ClaimAccessor(org.springframework.security.oauth2.core.ClaimAccessor) DefaultOAuth2TokenContext(org.springframework.security.oauth2.server.authorization.DefaultOAuth2TokenContext) OAuth2TokenContext(org.springframework.security.oauth2.server.authorization.OAuth2TokenContext) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) Jwt(org.springframework.security.oauth2.jwt.Jwt) Instant(java.time.Instant) OAuth2Authorization(org.springframework.security.oauth2.server.authorization.OAuth2Authorization) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) DefaultOAuth2TokenContext(org.springframework.security.oauth2.server.authorization.DefaultOAuth2TokenContext) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) Principal(java.security.Principal)

Example 2 with ClaimAccessor

use of org.springframework.security.oauth2.core.ClaimAccessor in project spring-authorization-server by spring-projects.

the class OAuth2AuthorizationCodeAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
    OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(authorizationCodeAuthentication);
    RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
    OAuth2Authorization authorization = this.authorizationService.findByToken(authorizationCodeAuthentication.getCode(), AUTHORIZATION_CODE_TOKEN_TYPE);
    if (authorization == null) {
        throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);
    }
    OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = authorization.getToken(OAuth2AuthorizationCode.class);
    OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(OAuth2AuthorizationRequest.class.getName());
    if (!registeredClient.getClientId().equals(authorizationRequest.getClientId())) {
        if (!authorizationCode.isInvalidated()) {
            // Invalidate the authorization code given that a different client is attempting to use it
            authorization = OAuth2AuthenticationProviderUtils.invalidate(authorization, authorizationCode.getToken());
            this.authorizationService.save(authorization);
        }
        throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);
    }
    if (StringUtils.hasText(authorizationRequest.getRedirectUri()) && !authorizationRequest.getRedirectUri().equals(authorizationCodeAuthentication.getRedirectUri())) {
        throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);
    }
    if (!authorizationCode.isActive()) {
        throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);
    }
    // @formatter:off
    DefaultOAuth2TokenContext.Builder tokenContextBuilder = DefaultOAuth2TokenContext.builder().registeredClient(registeredClient).principal(authorization.getAttribute(Principal.class.getName())).providerContext(ProviderContextHolder.getProviderContext()).authorization(authorization).authorizedScopes(authorization.getAttribute(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME)).authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).authorizationGrant(authorizationCodeAuthentication);
    // @formatter:on
    OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization.from(authorization);
    // ----- Access token -----
    OAuth2TokenContext tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.ACCESS_TOKEN).build();
    OAuth2Token generatedAccessToken = this.tokenGenerator.generate(tokenContext);
    if (generatedAccessToken == null) {
        OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, "The token generator failed to generate the access token.", ERROR_URI);
        throw new OAuth2AuthenticationException(error);
    }
    OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, generatedAccessToken.getTokenValue(), generatedAccessToken.getIssuedAt(), generatedAccessToken.getExpiresAt(), tokenContext.getAuthorizedScopes());
    if (generatedAccessToken instanceof ClaimAccessor) {
        authorizationBuilder.token(accessToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, ((ClaimAccessor) generatedAccessToken).getClaims()));
    } else {
        authorizationBuilder.accessToken(accessToken);
    }
    // ----- Refresh token -----
    OAuth2RefreshToken refreshToken = null;
    if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.REFRESH_TOKEN) && // Do not issue refresh token to public client
    !clientPrincipal.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.NONE)) {
        if (this.refreshTokenGenerator != null) {
            Instant issuedAt = Instant.now();
            Instant expiresAt = issuedAt.plus(registeredClient.getTokenSettings().getRefreshTokenTimeToLive());
            refreshToken = new OAuth2RefreshToken(this.refreshTokenGenerator.get(), issuedAt, expiresAt);
        } else {
            tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.REFRESH_TOKEN).build();
            OAuth2Token generatedRefreshToken = this.tokenGenerator.generate(tokenContext);
            if (!(generatedRefreshToken instanceof OAuth2RefreshToken)) {
                OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, "The token generator failed to generate the refresh token.", ERROR_URI);
                throw new OAuth2AuthenticationException(error);
            }
            refreshToken = (OAuth2RefreshToken) generatedRefreshToken;
        }
        authorizationBuilder.refreshToken(refreshToken);
    }
    // ----- ID token -----
    OidcIdToken idToken;
    if (authorizationRequest.getScopes().contains(OidcScopes.OPENID)) {
        tokenContext = tokenContextBuilder.tokenType(ID_TOKEN_TOKEN_TYPE).build();
        OAuth2Token generatedIdToken = this.tokenGenerator.generate(tokenContext);
        if (!(generatedIdToken instanceof Jwt)) {
            OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, "The token generator failed to generate the ID token.", ERROR_URI);
            throw new OAuth2AuthenticationException(error);
        }
        idToken = new OidcIdToken(generatedIdToken.getTokenValue(), generatedIdToken.getIssuedAt(), generatedIdToken.getExpiresAt(), ((Jwt) generatedIdToken).getClaims());
        authorizationBuilder.token(idToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims()));
    } else {
        idToken = null;
    }
    authorization = authorizationBuilder.build();
    // Invalidate the authorization code as it can only be used once
    authorization = OAuth2AuthenticationProviderUtils.invalidate(authorization, authorizationCode.getToken());
    this.authorizationService.save(authorization);
    Map<String, Object> additionalParameters = Collections.emptyMap();
    if (idToken != null) {
        additionalParameters = new HashMap<>();
        additionalParameters.put(OidcParameterNames.ID_TOKEN, idToken.getTokenValue());
    }
    return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, accessToken, refreshToken, additionalParameters);
}
Also used : OidcIdToken(org.springframework.security.oauth2.core.oidc.OidcIdToken) OAuth2Token(org.springframework.security.oauth2.core.OAuth2Token) ClaimAccessor(org.springframework.security.oauth2.core.ClaimAccessor) DefaultOAuth2TokenContext(org.springframework.security.oauth2.server.authorization.DefaultOAuth2TokenContext) OAuth2TokenContext(org.springframework.security.oauth2.server.authorization.OAuth2TokenContext) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) Jwt(org.springframework.security.oauth2.jwt.Jwt) Instant(java.time.Instant) OAuth2Authorization(org.springframework.security.oauth2.server.authorization.OAuth2Authorization) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) OAuth2AuthorizationCode(org.springframework.security.oauth2.core.OAuth2AuthorizationCode) DefaultOAuth2TokenContext(org.springframework.security.oauth2.server.authorization.DefaultOAuth2TokenContext) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) Principal(java.security.Principal)

Example 3 with ClaimAccessor

use of org.springframework.security.oauth2.core.ClaimAccessor in project spring-authorization-server by spring-projects.

the class OidcClientRegistrationAuthenticationProvider method registerAccessToken.

private OAuth2Authorization registerAccessToken(RegisteredClient registeredClient) {
    OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, registeredClient.getClientAuthenticationMethods().iterator().next(), registeredClient.getClientSecret());
    Set<String> authorizedScopes = new HashSet<>();
    authorizedScopes.add(DEFAULT_CLIENT_CONFIGURATION_AUTHORIZED_SCOPE);
    authorizedScopes = Collections.unmodifiableSet(authorizedScopes);
    // @formatter:off
    OAuth2TokenContext tokenContext = DefaultOAuth2TokenContext.builder().registeredClient(registeredClient).principal(clientPrincipal).providerContext(ProviderContextHolder.getProviderContext()).authorizedScopes(authorizedScopes).tokenType(OAuth2TokenType.ACCESS_TOKEN).authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).build();
    // @formatter:on
    OAuth2Token registrationAccessToken = this.tokenGenerator.generate(tokenContext);
    if (registrationAccessToken == null) {
        OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, "The token generator failed to generate the registration access token.", ERROR_URI);
        throw new OAuth2AuthenticationException(error);
    }
    OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, registrationAccessToken.getTokenValue(), registrationAccessToken.getIssuedAt(), registrationAccessToken.getExpiresAt(), tokenContext.getAuthorizedScopes());
    // @formatter:off
    OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization.withRegisteredClient(registeredClient).principalName(registeredClient.getClientId()).authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).attribute(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME, authorizedScopes);
    // @formatter:on
    if (registrationAccessToken instanceof ClaimAccessor) {
        authorizationBuilder.token(accessToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, ((ClaimAccessor) registrationAccessToken).getClaims()));
    } else {
        authorizationBuilder.accessToken(accessToken);
    }
    OAuth2Authorization authorization = authorizationBuilder.build();
    this.authorizationService.save(authorization);
    return authorization;
}
Also used : ClaimAccessor(org.springframework.security.oauth2.core.ClaimAccessor) DefaultOAuth2TokenContext(org.springframework.security.oauth2.server.authorization.DefaultOAuth2TokenContext) OAuth2TokenContext(org.springframework.security.oauth2.server.authorization.OAuth2TokenContext) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2Token(org.springframework.security.oauth2.core.OAuth2Token) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2Authorization(org.springframework.security.oauth2.server.authorization.OAuth2Authorization) OAuth2ClientAuthenticationToken(org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) HashSet(java.util.HashSet)

Example 4 with ClaimAccessor

use of org.springframework.security.oauth2.core.ClaimAccessor in project herodotus-engine by herodotus-cloud.

the class OAuth2ResourceOwnerPasswordAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    OAuth2ResourceOwnerPasswordAuthenticationToken resourceOwnerPasswordAuthentication = (OAuth2ResourceOwnerPasswordAuthenticationToken) authentication;
    OAuth2ClientAuthenticationToken clientPrincipal = OAuth2AuthenticationProviderUtils.getAuthenticatedClientElseThrowInvalidClient(resourceOwnerPasswordAuthentication);
    RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
    if (!registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.PASSWORD)) {
        throw new OAuth2AuthenticationException(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT);
    }
    Map<String, Object> additionalParameters = resourceOwnerPasswordAuthentication.getAdditionalParameters();
    String username = (String) additionalParameters.get(OAuth2ParameterNames.USERNAME);
    String password = (String) additionalParameters.get(OAuth2ParameterNames.PASSWORD);
    Authentication usernamePasswordAuthentication = null;
    try {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        usernamePasswordAuthentication = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        log.debug("[Herodotus] |- Resource Owner Password username and password authenticate success :[{}]", usernamePasswordAuthentication);
    } catch (AccountStatusException | BadCredentialsException ase) {
        // covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
        OAuth2EndpointUtils.throwError(OAuth2ErrorCodes.INVALID_GRANT, ase.getMessage(), OAuth2EndpointUtils.ACCESS_TOKEN_REQUEST_ERROR_URI);
    }
    // If the username/password are wrong the spec says we should send 400/invalid grant
    // Default to configured scopes
    Set<String> authorizedScopes = registeredClient.getScopes();
    if (!CollectionUtils.isEmpty(resourceOwnerPasswordAuthentication.getScopes())) {
        for (String requestedScope : resourceOwnerPasswordAuthentication.getScopes()) {
            if (!registeredClient.getScopes().contains(requestedScope)) {
                throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_SCOPE);
            }
        }
        authorizedScopes = new LinkedHashSet<>(resourceOwnerPasswordAuthentication.getScopes());
    }
    // @formatter:off
    DefaultOAuth2TokenContext.Builder tokenContextBuilder = DefaultOAuth2TokenContext.builder().registeredClient(registeredClient).principal(usernamePasswordAuthentication).providerContext(ProviderContextHolder.getProviderContext()).authorizedScopes(authorizedScopes).tokenType(OAuth2TokenType.ACCESS_TOKEN).authorizationGrantType(AuthorizationGrantType.PASSWORD).authorizationGrant(resourceOwnerPasswordAuthentication);
    // @formatter:on
    OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization.withRegisteredClient(registeredClient).principalName(usernamePasswordAuthentication.getName()).authorizationGrantType(AuthorizationGrantType.PASSWORD).attribute(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME, authorizedScopes);
    // ----- Access token -----
    OAuth2TokenContext tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.ACCESS_TOKEN).build();
    OAuth2Token generatedAccessToken = this.tokenGenerator.generate(tokenContext);
    if (generatedAccessToken == null) {
        OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, "The token generator failed to generate the access token.", ERROR_URI);
        throw new OAuth2AuthenticationException(error);
    }
    OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, generatedAccessToken.getTokenValue(), generatedAccessToken.getIssuedAt(), generatedAccessToken.getExpiresAt(), tokenContext.getAuthorizedScopes());
    if (generatedAccessToken instanceof ClaimAccessor) {
        authorizationBuilder.token(accessToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, ((ClaimAccessor) generatedAccessToken).getClaims()));
    } else {
        authorizationBuilder.accessToken(accessToken);
    }
    // ----- Refresh token -----
    OAuth2RefreshToken refreshToken = null;
    if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.REFRESH_TOKEN) && // Do not issue refresh token to public client
    !clientPrincipal.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.NONE)) {
        tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.REFRESH_TOKEN).build();
        OAuth2Token generatedRefreshToken = this.tokenGenerator.generate(tokenContext);
        if (!(generatedRefreshToken instanceof OAuth2RefreshToken)) {
            OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, "The token generator failed to generate the refresh token.", ERROR_URI);
            throw new OAuth2AuthenticationException(error);
        }
        refreshToken = (OAuth2RefreshToken) generatedRefreshToken;
        authorizationBuilder.refreshToken(refreshToken);
    }
    OAuth2Authorization authorization = authorizationBuilder.build();
    this.authorizationService.save(authorization);
    log.debug("[Herodotus] |- Resource Owner Password returning OAuth2AccessTokenAuthenticationToken.");
    return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, accessToken, refreshToken);
}
Also used : OAuth2TokenContext(org.springframework.security.oauth2.server.authorization.OAuth2TokenContext) DefaultOAuth2TokenContext(org.springframework.security.oauth2.server.authorization.token.DefaultOAuth2TokenContext) OAuth2AccessTokenAuthenticationToken(org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken) OAuth2ClientAuthenticationToken(org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken) OAuth2Authorization(org.springframework.security.oauth2.server.authorization.OAuth2Authorization) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) Authentication(org.springframework.security.core.Authentication) DefaultOAuth2TokenContext(org.springframework.security.oauth2.server.authorization.token.DefaultOAuth2TokenContext)

Example 5 with ClaimAccessor

use of org.springframework.security.oauth2.core.ClaimAccessor in project spring-authorization-server by spring-projects.

the class OAuth2AccessTokenGeneratorTests method generateWhenReferenceAccessTokenTypeThenReturnAccessToken.

@Test
public void generateWhenReferenceAccessTokenTypeThenReturnAccessToken() {
    // @formatter:off
    TokenSettings tokenSettings = TokenSettings.builder().accessTokenFormat(OAuth2TokenFormat.REFERENCE).build();
    RegisteredClient registeredClient = TestRegisteredClients.registeredClient().tokenSettings(tokenSettings).build();
    // @formatter:on
    OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
    Authentication principal = authorization.getAttribute(Principal.class.getName());
    OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
    OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(OAuth2AuthorizationRequest.class.getName());
    OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken("code", clientPrincipal, authorizationRequest.getRedirectUri(), null);
    // @formatter:off
    OAuth2TokenContext tokenContext = DefaultOAuth2TokenContext.builder().registeredClient(registeredClient).principal(principal).providerContext(this.providerContext).authorization(authorization).authorizedScopes(authorization.getAttribute(OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME)).tokenType(OAuth2TokenType.ACCESS_TOKEN).authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).authorizationGrant(authentication).build();
    // @formatter:on
    OAuth2AccessToken accessToken = this.accessTokenGenerator.generate(tokenContext);
    assertThat(accessToken).isNotNull();
    Instant issuedAt = Instant.now();
    Instant expiresAt = issuedAt.plus(tokenContext.getRegisteredClient().getTokenSettings().getAccessTokenTimeToLive());
    assertThat(accessToken.getIssuedAt()).isBetween(issuedAt.minusSeconds(1), issuedAt.plusSeconds(1));
    assertThat(accessToken.getExpiresAt()).isBetween(expiresAt.minusSeconds(1), expiresAt.plusSeconds(1));
    assertThat(accessToken.getScopes()).isEqualTo(tokenContext.getAuthorizedScopes());
    assertThat(accessToken).isInstanceOf(ClaimAccessor.class);
    OAuth2TokenClaimAccessor accessTokenClaims = ((ClaimAccessor) accessToken)::getClaims;
    assertThat(accessTokenClaims.getClaims()).isNotEmpty();
    assertThat(accessTokenClaims.getIssuer().toExternalForm()).isEqualTo(tokenContext.getProviderContext().getIssuer());
    assertThat(accessTokenClaims.getSubject()).isEqualTo(tokenContext.getPrincipal().getName());
    assertThat(accessTokenClaims.getAudience()).isEqualTo(Collections.singletonList(tokenContext.getRegisteredClient().getClientId()));
    assertThat(accessTokenClaims.getIssuedAt()).isBetween(issuedAt.minusSeconds(1), issuedAt.plusSeconds(1));
    assertThat(accessTokenClaims.getExpiresAt()).isBetween(expiresAt.minusSeconds(1), expiresAt.plusSeconds(1));
    assertThat(accessTokenClaims.getNotBefore()).isBetween(issuedAt.minusSeconds(1), issuedAt.plusSeconds(1));
    assertThat(accessTokenClaims.getId()).isNotNull();
    Set<String> scopes = accessTokenClaims.getClaim(OAuth2ParameterNames.SCOPE);
    assertThat(scopes).isEqualTo(tokenContext.getAuthorizedScopes());
    ArgumentCaptor<OAuth2TokenClaimsContext> tokenClaimsContextCaptor = ArgumentCaptor.forClass(OAuth2TokenClaimsContext.class);
    verify(this.accessTokenCustomizer).customize(tokenClaimsContextCaptor.capture());
    OAuth2TokenClaimsContext tokenClaimsContext = tokenClaimsContextCaptor.getValue();
    assertThat(tokenClaimsContext.getClaims()).isNotNull();
    assertThat(tokenClaimsContext.getRegisteredClient()).isEqualTo(tokenContext.getRegisteredClient());
    assertThat(tokenClaimsContext.<Authentication>getPrincipal()).isEqualTo(tokenContext.getPrincipal());
    assertThat(tokenClaimsContext.getProviderContext()).isEqualTo(tokenContext.getProviderContext());
    assertThat(tokenClaimsContext.getAuthorization()).isEqualTo(tokenContext.getAuthorization());
    assertThat(tokenClaimsContext.getAuthorizedScopes()).isEqualTo(tokenContext.getAuthorizedScopes());
    assertThat(tokenClaimsContext.getTokenType()).isEqualTo(tokenContext.getTokenType());
    assertThat(tokenClaimsContext.getAuthorizationGrantType()).isEqualTo(tokenContext.getAuthorizationGrantType());
    assertThat(tokenClaimsContext.<Authentication>getAuthorizationGrant()).isEqualTo(tokenContext.getAuthorizationGrant());
}
Also used : TokenSettings(org.springframework.security.oauth2.server.authorization.config.TokenSettings) Instant(java.time.Instant) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeAuthenticationToken) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) OAuth2TokenClaimAccessor(org.springframework.security.oauth2.core.OAuth2TokenClaimAccessor) ClaimAccessor(org.springframework.security.oauth2.core.ClaimAccessor) Authentication(org.springframework.security.core.Authentication) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2TokenClaimAccessor(org.springframework.security.oauth2.core.OAuth2TokenClaimAccessor) OAuth2ClientAuthenticationToken(org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Principal(java.security.Principal) Test(org.junit.Test)

Aggregations

ClaimAccessor (org.springframework.security.oauth2.core.ClaimAccessor)5 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)5 OAuth2Authorization (org.springframework.security.oauth2.server.authorization.OAuth2Authorization)5 OAuth2TokenContext (org.springframework.security.oauth2.server.authorization.OAuth2TokenContext)5 RegisteredClient (org.springframework.security.oauth2.server.authorization.client.RegisteredClient)5 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)4 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)4 OAuth2Token (org.springframework.security.oauth2.core.OAuth2Token)4 DefaultOAuth2TokenContext (org.springframework.security.oauth2.server.authorization.DefaultOAuth2TokenContext)4 Principal (java.security.Principal)3 Instant (java.time.Instant)3 OAuth2ClientAuthenticationToken (org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken)3 Authentication (org.springframework.security.core.Authentication)2 OAuth2RefreshToken (org.springframework.security.oauth2.core.OAuth2RefreshToken)2 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)2 OidcIdToken (org.springframework.security.oauth2.core.oidc.OidcIdToken)2 Jwt (org.springframework.security.oauth2.jwt.Jwt)2 HashSet (java.util.HashSet)1 Test (org.junit.Test)1 OAuth2AuthorizationCode (org.springframework.security.oauth2.core.OAuth2AuthorizationCode)1