Search in sources :

Example 31 with OAuth2ClientAuthenticationToken

use of org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken in project spring-authorization-server by spring-projects.

the class OAuth2ClientAuthenticationProvider method authenticatePkceIfAvailable.

private boolean authenticatePkceIfAvailable(OAuth2ClientAuthenticationToken clientAuthentication, RegisteredClient registeredClient) {
    Map<String, Object> parameters = clientAuthentication.getAdditionalParameters();
    if (!authorizationCodeGrant(parameters)) {
        return false;
    }
    OAuth2Authorization authorization = this.authorizationService.findByToken((String) parameters.get(OAuth2ParameterNames.CODE), AUTHORIZATION_CODE_TOKEN_TYPE);
    if (authorization == null) {
        throwInvalidGrant(OAuth2ParameterNames.CODE);
    }
    OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(OAuth2AuthorizationRequest.class.getName());
    String codeChallenge = (String) authorizationRequest.getAdditionalParameters().get(PkceParameterNames.CODE_CHALLENGE);
    if (!StringUtils.hasText(codeChallenge)) {
        if (registeredClient.getClientSettings().isRequireProofKey()) {
            throwInvalidGrant(PkceParameterNames.CODE_CHALLENGE);
        } else {
            return false;
        }
    }
    String codeChallengeMethod = (String) authorizationRequest.getAdditionalParameters().get(PkceParameterNames.CODE_CHALLENGE_METHOD);
    String codeVerifier = (String) parameters.get(PkceParameterNames.CODE_VERIFIER);
    if (!codeVerifierValid(codeVerifier, codeChallenge, codeChallengeMethod)) {
        throwInvalidGrant(PkceParameterNames.CODE_VERIFIER);
    }
    return true;
}
Also used : OAuth2Authorization(org.springframework.security.oauth2.server.authorization.OAuth2Authorization) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)

Example 32 with OAuth2ClientAuthenticationToken

use of org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken 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 33 with OAuth2ClientAuthenticationToken

use of org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken 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 34 with OAuth2ClientAuthenticationToken

use of org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken in project spring-authorization-server by spring-projects.

the class OAuth2TokenEndpointFilterTests method doFilterWhenCustomAuthenticationSuccessHandlerThenUsed.

@Test
public void doFilterWhenCustomAuthenticationSuccessHandlerThenUsed() throws Exception {
    AuthenticationSuccessHandler authenticationSuccessHandler = mock(AuthenticationSuccessHandler.class);
    this.filter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
    RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
    Authentication clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
    OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", Instant.now(), Instant.now().plus(Duration.ofHours(1)), new HashSet<>(Arrays.asList("scope1", "scope2")));
    OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, accessToken);
    when(this.authenticationManager.authenticate(any())).thenReturn(accessTokenAuthentication);
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(clientPrincipal);
    SecurityContextHolder.setContext(securityContext);
    MockHttpServletRequest request = createAuthorizationCodeTokenRequest(registeredClient);
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterChain filterChain = mock(FilterChain.class);
    this.filter.doFilter(request, response, filterChain);
    verify(authenticationSuccessHandler).onAuthenticationSuccess(any(), any(), any());
}
Also used : AuthenticationSuccessHandler(org.springframework.security.web.authentication.AuthenticationSuccessHandler) OAuth2AccessTokenAuthenticationToken(org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken) Authentication(org.springframework.security.core.Authentication) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) FilterChain(javax.servlet.FilterChain) SecurityContext(org.springframework.security.core.context.SecurityContext) OAuth2ClientAuthenticationToken(org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) Test(org.junit.Test)

Example 35 with OAuth2ClientAuthenticationToken

use of org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken in project spring-authorization-server by spring-projects.

the class OAuth2TokenEndpointFilterTests method doFilterWhenClientCredentialsTokenRequestThenAccessTokenResponse.

@Test
public void doFilterWhenClientCredentialsTokenRequestThenAccessTokenResponse() throws Exception {
    RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build();
    Authentication clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
    OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", Instant.now(), Instant.now().plus(Duration.ofHours(1)), new HashSet<>(Arrays.asList("scope1", "scope2")));
    OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, accessToken);
    when(this.authenticationManager.authenticate(any())).thenReturn(accessTokenAuthentication);
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(clientPrincipal);
    SecurityContextHolder.setContext(securityContext);
    MockHttpServletRequest request = createClientCredentialsTokenRequest(registeredClient);
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterChain filterChain = mock(FilterChain.class);
    this.filter.doFilter(request, response, filterChain);
    verifyNoInteractions(filterChain);
    ArgumentCaptor<OAuth2ClientCredentialsAuthenticationToken> clientCredentialsAuthenticationCaptor = ArgumentCaptor.forClass(OAuth2ClientCredentialsAuthenticationToken.class);
    verify(this.authenticationManager).authenticate(clientCredentialsAuthenticationCaptor.capture());
    OAuth2ClientCredentialsAuthenticationToken clientCredentialsAuthentication = clientCredentialsAuthenticationCaptor.getValue();
    assertThat(clientCredentialsAuthentication.getPrincipal()).isEqualTo(clientPrincipal);
    assertThat(clientCredentialsAuthentication.getScopes()).isEqualTo(registeredClient.getScopes());
    assertThat(clientCredentialsAuthentication.getAdditionalParameters()).containsExactly(entry("custom-param-1", "custom-value-1"));
    assertThat(clientCredentialsAuthentication.getDetails()).asInstanceOf(type(WebAuthenticationDetails.class)).extracting(WebAuthenticationDetails::getRemoteAddress).isEqualTo(REMOTE_ADDRESS);
    assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
    // For gh-281, check that expires_in is a number
    assertThat(new ObjectMapper().readValue(response.getContentAsByteArray(), Map.class).get(OAuth2ParameterNames.EXPIRES_IN)).isInstanceOf(Number.class);
    OAuth2AccessTokenResponse accessTokenResponse = readAccessTokenResponse(response);
    OAuth2AccessToken accessTokenResult = accessTokenResponse.getAccessToken();
    assertThat(accessTokenResult.getTokenType()).isEqualTo(accessToken.getTokenType());
    assertThat(accessTokenResult.getTokenValue()).isEqualTo(accessToken.getTokenValue());
    assertThat(accessTokenResult.getIssuedAt()).isBetween(accessToken.getIssuedAt().minusSeconds(1), accessToken.getIssuedAt().plusSeconds(1));
    assertThat(accessTokenResult.getExpiresAt()).isBetween(accessToken.getExpiresAt().minusSeconds(1), accessToken.getExpiresAt().plusSeconds(1));
    assertThat(accessTokenResult.getScopes()).isEqualTo(accessToken.getScopes());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2ClientCredentialsAuthenticationToken(org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientCredentialsAuthenticationToken) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) FilterChain(javax.servlet.FilterChain) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) OAuth2AccessTokenAuthenticationToken(org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken) Authentication(org.springframework.security.core.Authentication) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) SecurityContext(org.springframework.security.core.context.SecurityContext) OAuth2ClientAuthenticationToken(org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken) Map(java.util.Map) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Aggregations

RegisteredClient (org.springframework.security.oauth2.server.authorization.client.RegisteredClient)104 Test (org.junit.Test)102 OAuth2Authorization (org.springframework.security.oauth2.server.authorization.OAuth2Authorization)69 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)51 Instant (java.time.Instant)38 Authentication (org.springframework.security.core.Authentication)38 ClientAuthenticationMethod (org.springframework.security.oauth2.core.ClientAuthenticationMethod)32 OAuth2TokenType (org.springframework.security.oauth2.core.OAuth2TokenType)32 Jwt (org.springframework.security.oauth2.jwt.Jwt)32 OAuth2ClientAuthenticationToken (org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken)32 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)31 Assertions.assertThatThrownBy (org.assertj.core.api.Assertions.assertThatThrownBy)31 TestRegisteredClients (org.springframework.security.oauth2.server.authorization.client.TestRegisteredClients)31 HashMap (java.util.HashMap)30 AuthorizationGrantType (org.springframework.security.oauth2.core.AuthorizationGrantType)30 OAuth2ParameterNames (org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames)30 ProviderSettings (org.springframework.security.oauth2.server.authorization.config.ProviderSettings)30 ChronoUnit (java.time.temporal.ChronoUnit)29 Before (org.junit.Before)29 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)29