Search in sources :

Example 1 with OAuth2TokenIntrospection

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

the class OAuth2TokenIntrospectionAuthenticationProvider method withActiveTokenClaims.

private static OAuth2TokenIntrospection withActiveTokenClaims(OAuth2Authorization.Token<AbstractOAuth2Token> authorizedToken, RegisteredClient authorizedClient) {
    OAuth2TokenIntrospection.Builder tokenClaims = OAuth2TokenIntrospection.builder(true).clientId(authorizedClient.getClientId());
    // TODO Set "username"
    AbstractOAuth2Token token = authorizedToken.getToken();
    if (token.getIssuedAt() != null) {
        tokenClaims.issuedAt(token.getIssuedAt());
    }
    if (token.getExpiresAt() != null) {
        tokenClaims.expiresAt(token.getExpiresAt());
    }
    if (OAuth2AccessToken.class.isAssignableFrom(token.getClass())) {
        OAuth2AccessToken accessToken = (OAuth2AccessToken) token;
        tokenClaims.scopes(scopes -> scopes.addAll(accessToken.getScopes()));
        tokenClaims.tokenType(accessToken.getTokenType().getValue());
        if (!CollectionUtils.isEmpty(authorizedToken.getClaims())) {
            OAuth2TokenClaimAccessor accessTokenClaims = authorizedToken::getClaims;
            Instant notBefore = accessTokenClaims.getNotBefore();
            if (notBefore != null) {
                tokenClaims.notBefore(notBefore);
            }
            tokenClaims.subject(accessTokenClaims.getSubject());
            List<String> audience = accessTokenClaims.getAudience();
            if (!CollectionUtils.isEmpty(audience)) {
                tokenClaims.audiences(audiences -> audiences.addAll(audience));
            }
            URL issuer = accessTokenClaims.getIssuer();
            if (issuer != null) {
                tokenClaims.issuer(issuer.toExternalForm());
            }
            String jti = accessTokenClaims.getId();
            if (StringUtils.hasText(jti)) {
                tokenClaims.id(jti);
            }
        }
    }
    return tokenClaims.build();
}
Also used : OAuth2TokenIntrospection(org.springframework.security.oauth2.core.OAuth2TokenIntrospection) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2TokenClaimAccessor(org.springframework.security.oauth2.core.OAuth2TokenClaimAccessor) Instant(java.time.Instant) AbstractOAuth2Token(org.springframework.security.oauth2.core.AbstractOAuth2Token) URL(java.net.URL)

Example 2 with OAuth2TokenIntrospection

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

the class OAuth2TokenIntrospectionTests method requestWhenObtainReferenceAccessTokenAndIntrospectThenActive.

@Test
public void requestWhenObtainReferenceAccessTokenAndIntrospectThenActive() throws Exception {
    this.spring.register(AuthorizationServerConfiguration.class).autowire();
    // @formatter:off
    TokenSettings tokenSettings = TokenSettings.builder().accessTokenFormat(OAuth2TokenFormat.REFERENCE).build();
    RegisteredClient authorizedRegisteredClient = TestRegisteredClients.registeredClient().tokenSettings(tokenSettings).build();
    // @formatter:on
    this.registeredClientRepository.save(authorizedRegisteredClient);
    OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(authorizedRegisteredClient).build();
    this.authorizationService.save(authorization);
    // @formatter:off
    MvcResult mvcResult = this.mvc.perform(post(providerSettings.getTokenEndpoint()).params(getAuthorizationCodeTokenRequestParameters(authorizedRegisteredClient, authorization)).header(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(authorizedRegisteredClient))).andExpect(status().isOk()).andReturn();
    // @formatter:on
    OAuth2AccessTokenResponse accessTokenResponse = readAccessTokenResponse(mvcResult);
    OAuth2AccessToken accessToken = accessTokenResponse.getAccessToken();
    RegisteredClient introspectRegisteredClient = TestRegisteredClients.registeredClient2().build();
    this.registeredClientRepository.save(introspectRegisteredClient);
    // @formatter:off
    mvcResult = this.mvc.perform(post(providerSettings.getTokenIntrospectionEndpoint()).params(getTokenIntrospectionRequestParameters(accessToken, OAuth2TokenType.ACCESS_TOKEN)).header(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(introspectRegisteredClient))).andExpect(status().isOk()).andReturn();
    // @formatter:on
    OAuth2TokenIntrospection tokenIntrospectionResponse = readTokenIntrospectionResponse(mvcResult);
    ArgumentCaptor<OAuth2TokenClaimsContext> accessTokenClaimsContextCaptor = ArgumentCaptor.forClass(OAuth2TokenClaimsContext.class);
    verify(accessTokenCustomizer).customize(accessTokenClaimsContextCaptor.capture());
    OAuth2TokenClaimsContext accessTokenClaimsContext = accessTokenClaimsContextCaptor.getValue();
    OAuth2TokenClaimsSet accessTokenClaims = accessTokenClaimsContext.getClaims().build();
    assertThat(tokenIntrospectionResponse.isActive()).isTrue();
    assertThat(tokenIntrospectionResponse.getClientId()).isEqualTo(authorizedRegisteredClient.getClientId());
    assertThat(tokenIntrospectionResponse.getUsername()).isNull();
    assertThat(tokenIntrospectionResponse.getIssuedAt()).isBetween(accessTokenClaims.getIssuedAt().minusSeconds(1), accessTokenClaims.getIssuedAt().plusSeconds(1));
    assertThat(tokenIntrospectionResponse.getExpiresAt()).isBetween(accessTokenClaims.getExpiresAt().minusSeconds(1), accessTokenClaims.getExpiresAt().plusSeconds(1));
    List<String> scopes = new ArrayList<>(accessTokenClaims.getClaim(OAuth2ParameterNames.SCOPE));
    assertThat(tokenIntrospectionResponse.getScopes()).containsExactlyInAnyOrderElementsOf(scopes);
    assertThat(tokenIntrospectionResponse.getTokenType()).isEqualTo(accessToken.getTokenType().getValue());
    assertThat(tokenIntrospectionResponse.getNotBefore()).isBetween(accessTokenClaims.getNotBefore().minusSeconds(1), accessTokenClaims.getNotBefore().plusSeconds(1));
    assertThat(tokenIntrospectionResponse.getSubject()).isEqualTo(accessTokenClaims.getSubject());
    assertThat(tokenIntrospectionResponse.getAudience()).containsExactlyInAnyOrderElementsOf(accessTokenClaims.getAudience());
    assertThat(tokenIntrospectionResponse.getIssuer()).isEqualTo(accessTokenClaims.getIssuer());
    assertThat(tokenIntrospectionResponse.getId()).isEqualTo(accessTokenClaims.getId());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2TokenIntrospection(org.springframework.security.oauth2.core.OAuth2TokenIntrospection) OAuth2TokenClaimsContext(org.springframework.security.oauth2.server.authorization.OAuth2TokenClaimsContext) TokenSettings(org.springframework.security.oauth2.server.authorization.config.TokenSettings) ArrayList(java.util.ArrayList) OAuth2Authorization(org.springframework.security.oauth2.server.authorization.OAuth2Authorization) MvcResult(org.springframework.test.web.servlet.MvcResult) OAuth2AuthorizationServerConfiguration(org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2TokenClaimsSet(org.springframework.security.oauth2.core.OAuth2TokenClaimsSet) Test(org.junit.Test)

Example 3 with OAuth2TokenIntrospection

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

the class OAuth2TokenIntrospectionTests method requestWhenIntrospectValidAccessTokenThenActive.

@Test
public void requestWhenIntrospectValidAccessTokenThenActive() throws Exception {
    this.spring.register(AuthorizationServerConfiguration.class).autowire();
    RegisteredClient introspectRegisteredClient = TestRegisteredClients.registeredClient2().clientSecret("secret-2").build();
    this.registeredClientRepository.save(introspectRegisteredClient);
    RegisteredClient authorizedRegisteredClient = TestRegisteredClients.registeredClient().build();
    Instant issuedAt = Instant.now();
    Instant expiresAt = issuedAt.plus(Duration.ofHours(1));
    OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token", issuedAt, expiresAt, new HashSet<>(Arrays.asList("scope1", "scope2")));
    // @formatter:off
    OAuth2TokenClaimsSet accessTokenClaims = OAuth2TokenClaimsSet.builder().issuer("https://provider.com").subject("subject").audience(Collections.singletonList(authorizedRegisteredClient.getClientId())).issuedAt(issuedAt).notBefore(issuedAt).expiresAt(expiresAt).id("id").build();
    // @formatter:on
    OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(authorizedRegisteredClient, accessToken, accessTokenClaims.getClaims()).build();
    this.registeredClientRepository.save(authorizedRegisteredClient);
    this.authorizationService.save(authorization);
    // @formatter:off
    MvcResult mvcResult = this.mvc.perform(post(providerSettings.getTokenIntrospectionEndpoint()).params(getTokenIntrospectionRequestParameters(accessToken, OAuth2TokenType.ACCESS_TOKEN)).header(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(introspectRegisteredClient))).andExpect(status().isOk()).andReturn();
    // @formatter:on
    OAuth2TokenIntrospection tokenIntrospectionResponse = readTokenIntrospectionResponse(mvcResult);
    assertThat(tokenIntrospectionResponse.isActive()).isTrue();
    assertThat(tokenIntrospectionResponse.getClientId()).isEqualTo(authorizedRegisteredClient.getClientId());
    assertThat(tokenIntrospectionResponse.getUsername()).isNull();
    assertThat(tokenIntrospectionResponse.getIssuedAt()).isBetween(accessTokenClaims.getIssuedAt().minusSeconds(1), accessTokenClaims.getIssuedAt().plusSeconds(1));
    assertThat(tokenIntrospectionResponse.getExpiresAt()).isBetween(accessTokenClaims.getExpiresAt().minusSeconds(1), accessTokenClaims.getExpiresAt().plusSeconds(1));
    assertThat(tokenIntrospectionResponse.getScopes()).containsExactlyInAnyOrderElementsOf(accessToken.getScopes());
    assertThat(tokenIntrospectionResponse.getTokenType()).isEqualTo(accessToken.getTokenType().getValue());
    assertThat(tokenIntrospectionResponse.getNotBefore()).isBetween(accessTokenClaims.getNotBefore().minusSeconds(1), accessTokenClaims.getNotBefore().plusSeconds(1));
    assertThat(tokenIntrospectionResponse.getSubject()).isEqualTo(accessTokenClaims.getSubject());
    assertThat(tokenIntrospectionResponse.getAudience()).containsExactlyInAnyOrderElementsOf(accessTokenClaims.getAudience());
    assertThat(tokenIntrospectionResponse.getIssuer()).isEqualTo(accessTokenClaims.getIssuer());
    assertThat(tokenIntrospectionResponse.getId()).isEqualTo(accessTokenClaims.getId());
}
Also used : OAuth2TokenIntrospection(org.springframework.security.oauth2.core.OAuth2TokenIntrospection) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2TokenClaimsSet(org.springframework.security.oauth2.core.OAuth2TokenClaimsSet) Instant(java.time.Instant) OAuth2Authorization(org.springframework.security.oauth2.server.authorization.OAuth2Authorization) MvcResult(org.springframework.test.web.servlet.MvcResult) OAuth2AuthorizationServerConfiguration(org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) Test(org.junit.Test)

Example 4 with OAuth2TokenIntrospection

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

the class OAuth2TokenIntrospectionHttpMessageConverterTests method writeInternalWhenWriteFailsThenThrowsException.

@Test
public void writeInternalWhenWriteFailsThenThrowsException() {
    String errorMessage = "this is not a valid converter";
    Converter<OAuth2TokenIntrospection, Map<String, Object>> failingConverter = source -> {
        throw new RuntimeException(errorMessage);
    };
    this.messageConverter.setTokenIntrospectionParametersConverter(failingConverter);
    OAuth2TokenIntrospection tokenClaims = OAuth2TokenIntrospection.builder().build();
    MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
    assertThatThrownBy(() -> this.messageConverter.writeInternal(tokenClaims, outputMessage)).isInstanceOf(HttpMessageNotWritableException.class).hasMessageContaining("An error occurred writing the Token Introspection Response").hasMessageContaining(errorMessage);
}
Also used : Converter(org.springframework.core.convert.converter.Converter) Arrays(java.util.Arrays) URL(java.net.URL) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Test(org.junit.Test) Instant(java.time.Instant) HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) MockClientHttpResponse(org.springframework.mock.http.client.MockClientHttpResponse) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) OAuth2TokenIntrospection(org.springframework.security.oauth2.core.OAuth2TokenIntrospection) HttpStatus(org.springframework.http.HttpStatus) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) Map(java.util.Map) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) TokenType(org.springframework.security.oauth2.core.OAuth2AccessToken.TokenType) MockHttpOutputMessage(org.springframework.mock.http.MockHttpOutputMessage) OAuth2TokenIntrospection(org.springframework.security.oauth2.core.OAuth2TokenIntrospection) MockHttpOutputMessage(org.springframework.mock.http.MockHttpOutputMessage) Map(java.util.Map) Test(org.junit.Test)

Example 5 with OAuth2TokenIntrospection

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

the class OAuth2TokenIntrospectionHttpMessageConverterTests method writeInternalWhenTokenIntrospectionThenSuccess.

@Test
public void writeInternalWhenTokenIntrospectionThenSuccess() {
    // @formatter:off
    OAuth2TokenIntrospection tokenClaims = OAuth2TokenIntrospection.builder(true).clientId("clientId1").username("username1").issuedAt(Instant.ofEpochSecond(1607633867)).expiresAt(Instant.ofEpochSecond(1607637467)).scope("scope1 scope2").tokenType(TokenType.BEARER.getValue()).notBefore(Instant.ofEpochSecond(1607633867)).subject("subject1").audience("audience1").audience("audience2").issuer("https://example.com/issuer1").id("jwtId1").build();
    // @formatter:on
    MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
    this.messageConverter.writeInternal(tokenClaims, outputMessage);
    String tokenIntrospectionResponse = outputMessage.getBodyAsString();
    assertThat(tokenIntrospectionResponse).contains("\"active\":true");
    assertThat(tokenIntrospectionResponse).contains("\"client_id\":\"clientId1\"");
    assertThat(tokenIntrospectionResponse).contains("\"username\":\"username1\"");
    assertThat(tokenIntrospectionResponse).contains("\"iat\":1607633867");
    assertThat(tokenIntrospectionResponse).contains("\"exp\":1607637467");
    assertThat(tokenIntrospectionResponse).contains("\"scope\":\"scope1 scope2\"");
    assertThat(tokenIntrospectionResponse).contains("\"token_type\":\"Bearer\"");
    assertThat(tokenIntrospectionResponse).contains("\"nbf\":1607633867");
    assertThat(tokenIntrospectionResponse).contains("\"sub\":\"subject1\"");
    assertThat(tokenIntrospectionResponse).contains("\"aud\":[\"audience1\",\"audience2\"]");
    assertThat(tokenIntrospectionResponse).contains("\"iss\":\"https://example.com/issuer1\"");
    assertThat(tokenIntrospectionResponse).contains("\"jti\":\"jwtId1\"");
}
Also used : OAuth2TokenIntrospection(org.springframework.security.oauth2.core.OAuth2TokenIntrospection) MockHttpOutputMessage(org.springframework.mock.http.MockHttpOutputMessage) Test(org.junit.Test)

Aggregations

OAuth2TokenIntrospection (org.springframework.security.oauth2.core.OAuth2TokenIntrospection)12 Test (org.junit.Test)9 RegisteredClient (org.springframework.security.oauth2.server.authorization.client.RegisteredClient)7 OAuth2Authorization (org.springframework.security.oauth2.server.authorization.OAuth2Authorization)6 Instant (java.time.Instant)5 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)5 URL (java.net.URL)3 MockClientHttpResponse (org.springframework.mock.http.client.MockClientHttpResponse)3 OAuth2AuthorizationServerConfiguration (org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration)3 Arrays (java.util.Arrays)2 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)2 Assertions.assertThatThrownBy (org.assertj.core.api.Assertions.assertThatThrownBy)2 HttpStatus (org.springframework.http.HttpStatus)2 MockHttpOutputMessage (org.springframework.mock.http.MockHttpOutputMessage)2 OAuth2RefreshToken (org.springframework.security.oauth2.core.OAuth2RefreshToken)2 OAuth2TokenClaimsSet (org.springframework.security.oauth2.core.OAuth2TokenClaimsSet)2 OAuth2TokenIntrospectionAuthenticationToken (org.springframework.security.oauth2.server.authorization.authentication.OAuth2TokenIntrospectionAuthenticationToken)2 MvcResult (org.springframework.test.web.servlet.MvcResult)2 Duration (java.time.Duration)1 ArrayList (java.util.ArrayList)1