Search in sources :

Example 1 with org.springframework.security.oauth2.client

use of org.springframework.security.oauth2.client in project goodsKill by techa03.

the class KeyConfig method configure.

// ... client configuration, etc.
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
    // @formatter:off
    TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
    List<TokenEnhancer> delegates = new ArrayList<>();
    delegates.add(tokenEnhancer());
    delegates.add(accessTokenConverter());
    // 配置JWT的内容增强器
    enhancerChain.setTokenEnhancers(delegates);
    endpoints.authenticationManager(authenticationManager).userDetailsService(// 配置加载用户信息的服务
    userDetailsService).accessTokenConverter(accessTokenConverter()).tokenEnhancer(enhancerChain);
// @formatter:on
}
Also used : TokenEnhancer(org.springframework.security.oauth2.provider.token.TokenEnhancer) TokenEnhancerChain(org.springframework.security.oauth2.provider.token.TokenEnhancerChain) ArrayList(java.util.ArrayList)

Example 2 with org.springframework.security.oauth2.client

use of org.springframework.security.oauth2.client in project powerauth-webflow by wultra.

the class OAuth2AuthorizationServerConfiguration method configureAuthorizationEndpoint.

/**
 * Configures authorization endpoint.
 * @param authorizationEndpoint Authorization endpoint.
 */
@Autowired
public void configureAuthorizationEndpoint(AuthorizationEndpoint authorizationEndpoint) {
    // WORKAROUND: Cancel the session just before the redirect
    DefaultRedirectResolver redirectResolver = new DefaultRedirectResolver() {

        @Override
        public String resolveRedirect(String requestedRedirect, ClientDetails client) throws OAuth2Exception {
            SecurityContextHolder.clearContext();
            return super.resolveRedirect(requestedRedirect, client);
        }
    };
    redirectResolver.setMatchPorts(false);
    authorizationEndpoint.setRedirectResolver(redirectResolver);
}
Also used : DefaultRedirectResolver(org.springframework.security.oauth2.provider.endpoint.DefaultRedirectResolver) ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) Autowired(org.springframework.beans.factory.annotation.Autowired)

Example 3 with org.springframework.security.oauth2.client

use of org.springframework.security.oauth2.client in project kg-search by HumanBrainProject.

the class OauthClient method serviceAccountWebClient.

@Bean
@Qualifier("asServiceAccount")
WebClient serviceAccountWebClient(ClientRegistrationRepository clientRegistrations, OAuth2AuthorizedClientService authorizedClientService) {
    AuthorizedClientServiceOAuth2AuthorizedClientManager clientManager = new AuthorizedClientServiceOAuth2AuthorizedClientManager(clientRegistrations, authorizedClientService);
    ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2 = new ServletOAuth2AuthorizedClientExchangeFilterFunction(clientManager);
    oauth2.setAuthorizationFailureHandler(new RemoveAuthorizedClientOAuth2AuthorizationFailureHandler((clientRegistrationId, principal, attributes) -> {
        logger.info("Resource server authorization failure for clientRegistrationId={}", clientRegistrationId);
        authorizedClientService.removeAuthorizedClient(clientRegistrationId, principal.getName());
    }));
    oauth2.setDefaultClientRegistrationId("kg");
    return WebClient.builder().exchangeStrategies(exchangeStrategies).apply(oauth2.oauth2Configuration()).filter((clientRequest, nextFilter) -> {
        ClientRequest updatedHeaders = ClientRequest.from(clientRequest).headers(h -> {
            h.put("Client-Authorization", h.get("Authorization"));
        }).build();
        return nextFilter.exchange(updatedHeaders);
    }).build();
}
Also used : Primary(org.springframework.context.annotation.Primary) Jackson2JsonDecoder(org.springframework.http.codec.json.Jackson2JsonDecoder) Logger(org.slf4j.Logger) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) LoggerFactory(org.slf4j.LoggerFactory) WebClient(org.springframework.web.reactive.function.client.WebClient) Jackson2JsonEncoder(org.springframework.http.codec.json.Jackson2JsonEncoder) AuthorizedClientServiceOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager) RemoveAuthorizedClientOAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.RemoveAuthorizedClientOAuth2AuthorizationFailureHandler) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) Configuration(org.springframework.context.annotation.Configuration) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) List(java.util.List) Qualifier(org.springframework.beans.factory.annotation.Qualifier) ExchangeStrategies(org.springframework.web.reactive.function.client.ExchangeStrategies) OAuth2AuthorizedClientService(org.springframework.security.oauth2.client.OAuth2AuthorizedClientService) ServletOAuth2AuthorizedClientExchangeFilterFunction(org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction) Bean(org.springframework.context.annotation.Bean) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) ServletOAuth2AuthorizedClientExchangeFilterFunction(org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction) RemoveAuthorizedClientOAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.RemoveAuthorizedClientOAuth2AuthorizationFailureHandler) AuthorizedClientServiceOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) Qualifier(org.springframework.beans.factory.annotation.Qualifier) Bean(org.springframework.context.annotation.Bean)

Example 4 with org.springframework.security.oauth2.client

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

the class OAuth2ClientAuthenticationProviderTests method authenticateWhenJwtClientAssertionAndMissingJwkSetUrlThenThrowOAuth2AuthenticationException.

@Test
public void authenticateWhenJwtClientAssertionAndMissingJwkSetUrlThenThrowOAuth2AuthenticationException() {
    // @formatter:off
    RegisteredClient registeredClient = TestRegisteredClients.registeredClient().clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT).clientSettings(ClientSettings.builder().tokenEndpointAuthenticationSigningAlgorithm(SignatureAlgorithm.RS256).build()).build();
    // @formatter:on
    when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))).thenReturn(registeredClient);
    OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(registeredClient.getClientId(), JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD, "jwt-assertion", null);
    assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)).isInstanceOf(OAuth2AuthenticationException.class).extracting(ex -> ((OAuth2AuthenticationException) ex).getError()).satisfies(error -> {
        assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
        assertThat(error.getDescription()).isEqualTo("Failed to find a Signature Verifier for Client: '" + registeredClient.getId() + "'. Check to ensure you have configured the JWK Set URL.");
    });
}
Also used : UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) RegisteredClientRepository(org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SecretKeySpec(javax.crypto.spec.SecretKeySpec) JWKSet(com.nimbusds.jose.jwk.JWKSet) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) MacAlgorithm(org.springframework.security.oauth2.jose.jws.MacAlgorithm) TestOAuth2Authorizations(org.springframework.security.oauth2.server.authorization.TestOAuth2Authorizations) Map(java.util.Map) Jwt(org.springframework.security.oauth2.jwt.Jwt) OctetSequenceKey(com.nimbusds.jose.jwk.OctetSequenceKey) ProviderSettings(org.springframework.security.oauth2.server.authorization.config.ProviderSettings) JWKSource(com.nimbusds.jose.jwk.source.JWKSource) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) Instant(java.time.Instant) StandardCharsets(java.nio.charset.StandardCharsets) NoOpPasswordEncoder(org.springframework.security.crypto.password.NoOpPasswordEncoder) SecretKey(javax.crypto.SecretKey) BadJwtException(org.springframework.security.oauth2.jwt.BadJwtException) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) SecurityContext(com.nimbusds.jose.proc.SecurityContext) OAuth2ParameterNames(org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames) PkceParameterNames(org.springframework.security.oauth2.core.endpoint.PkceParameterNames) HashMap(java.util.HashMap) JwtEncoder(org.springframework.security.oauth2.jwt.JwtEncoder) Mockito.spy(org.mockito.Mockito.spy) JwtClaimsSet(org.springframework.security.oauth2.jwt.JwtClaimsSet) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) ClientAuthenticationMethod(org.springframework.security.oauth2.core.ClientAuthenticationMethod) JwtValidationException(org.springframework.security.oauth2.jwt.JwtValidationException) ClientSettings(org.springframework.security.oauth2.server.authorization.config.ClientSettings) Before(org.junit.Before) OAuth2Authorization(org.springframework.security.oauth2.server.authorization.OAuth2Authorization) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) TestKeys(org.springframework.security.oauth2.jose.TestKeys) TestJwks(org.springframework.security.oauth2.jose.TestJwks) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) OAuth2ErrorCodes(org.springframework.security.oauth2.core.OAuth2ErrorCodes) NimbusJwsEncoder(org.springframework.security.oauth2.jwt.NimbusJwsEncoder) TestRegisteredClients(org.springframework.security.oauth2.server.authorization.client.TestRegisteredClients) OAuth2AuthorizationService(org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService) Mockito.verify(org.mockito.Mockito.verify) JoseHeader(org.springframework.security.oauth2.jwt.JoseHeader) ChronoUnit(java.time.temporal.ChronoUnit) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) SignatureAlgorithm(org.springframework.security.oauth2.jose.jws.SignatureAlgorithm) OAuth2TokenType(org.springframework.security.oauth2.core.OAuth2TokenType) Collections(java.util.Collections) AuthorizationGrantType(org.springframework.security.oauth2.core.AuthorizationGrantType) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) Test(org.junit.Test)

Example 5 with org.springframework.security.oauth2.client

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

the class OAuth2ClientAuthenticationProviderTests method authenticateWhenJwtClientAssertionAndMissingClientSecretThenThrowOAuth2AuthenticationException.

@Test
public void authenticateWhenJwtClientAssertionAndMissingClientSecretThenThrowOAuth2AuthenticationException() {
    // @formatter:off
    RegisteredClient registeredClient = TestRegisteredClients.registeredClient().clientSecret(null).clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT).clientSettings(ClientSettings.builder().tokenEndpointAuthenticationSigningAlgorithm(MacAlgorithm.HS256).build()).build();
    // @formatter:on
    when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))).thenReturn(registeredClient);
    OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(registeredClient.getClientId(), JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD, "jwt-assertion", null);
    assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)).isInstanceOf(OAuth2AuthenticationException.class).extracting(ex -> ((OAuth2AuthenticationException) ex).getError()).satisfies(error -> {
        assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
        assertThat(error.getDescription()).isEqualTo("Failed to find a Signature Verifier for Client: '" + registeredClient.getId() + "'. Check to ensure you have configured the client secret.");
    });
}
Also used : UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) RegisteredClientRepository(org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SecretKeySpec(javax.crypto.spec.SecretKeySpec) JWKSet(com.nimbusds.jose.jwk.JWKSet) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) MacAlgorithm(org.springframework.security.oauth2.jose.jws.MacAlgorithm) TestOAuth2Authorizations(org.springframework.security.oauth2.server.authorization.TestOAuth2Authorizations) Map(java.util.Map) Jwt(org.springframework.security.oauth2.jwt.Jwt) OctetSequenceKey(com.nimbusds.jose.jwk.OctetSequenceKey) ProviderSettings(org.springframework.security.oauth2.server.authorization.config.ProviderSettings) JWKSource(com.nimbusds.jose.jwk.source.JWKSource) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) Instant(java.time.Instant) StandardCharsets(java.nio.charset.StandardCharsets) NoOpPasswordEncoder(org.springframework.security.crypto.password.NoOpPasswordEncoder) SecretKey(javax.crypto.SecretKey) BadJwtException(org.springframework.security.oauth2.jwt.BadJwtException) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) SecurityContext(com.nimbusds.jose.proc.SecurityContext) OAuth2ParameterNames(org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames) PkceParameterNames(org.springframework.security.oauth2.core.endpoint.PkceParameterNames) HashMap(java.util.HashMap) JwtEncoder(org.springframework.security.oauth2.jwt.JwtEncoder) Mockito.spy(org.mockito.Mockito.spy) JwtClaimsSet(org.springframework.security.oauth2.jwt.JwtClaimsSet) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) ClientAuthenticationMethod(org.springframework.security.oauth2.core.ClientAuthenticationMethod) JwtValidationException(org.springframework.security.oauth2.jwt.JwtValidationException) ClientSettings(org.springframework.security.oauth2.server.authorization.config.ClientSettings) Before(org.junit.Before) OAuth2Authorization(org.springframework.security.oauth2.server.authorization.OAuth2Authorization) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) TestKeys(org.springframework.security.oauth2.jose.TestKeys) TestJwks(org.springframework.security.oauth2.jose.TestJwks) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) OAuth2ErrorCodes(org.springframework.security.oauth2.core.OAuth2ErrorCodes) NimbusJwsEncoder(org.springframework.security.oauth2.jwt.NimbusJwsEncoder) TestRegisteredClients(org.springframework.security.oauth2.server.authorization.client.TestRegisteredClients) OAuth2AuthorizationService(org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService) Mockito.verify(org.mockito.Mockito.verify) JoseHeader(org.springframework.security.oauth2.jwt.JoseHeader) ChronoUnit(java.time.temporal.ChronoUnit) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) SignatureAlgorithm(org.springframework.security.oauth2.jose.jws.SignatureAlgorithm) OAuth2TokenType(org.springframework.security.oauth2.core.OAuth2TokenType) Collections(java.util.Collections) AuthorizationGrantType(org.springframework.security.oauth2.core.AuthorizationGrantType) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) Test(org.junit.Test)

Aggregations

Test (org.junit.jupiter.api.Test)272 BaseClientDetails (org.springframework.security.oauth2.provider.client.BaseClientDetails)254 Test (org.junit.Test)197 Authentication (org.springframework.security.core.Authentication)130 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)118 ClientDetails (org.springframework.security.oauth2.provider.ClientDetails)117 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)108 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)83 HashMap (java.util.HashMap)81 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)69 Map (java.util.Map)68 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)68 BeforeEach (org.junit.jupiter.api.BeforeEach)65 HttpHeaders (org.springframework.http.HttpHeaders)64 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)63 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)63 Matchers.containsString (org.hamcrest.Matchers.containsString)62 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)62 RandomValueStringGenerator (org.springframework.security.oauth2.common.util.RandomValueStringGenerator)52 Date (java.util.Date)50