Search in sources :

Example 1 with InMemoryClientRegistrationRepository

use of org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository in project spring-security by spring-projects.

the class OAuth2AuthorizedClientArgumentResolverTests method setup.

@BeforeEach
public void setup() {
    this.authentication = new TestingAuthenticationToken(this.principalName, "password");
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(this.authentication);
    SecurityContextHolder.setContext(securityContext);
    // @formatter:off
    this.registration1 = ClientRegistration.withRegistrationId("client1").clientId("client-1").clientSecret("secret").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).redirectUri("{baseUrl}/login/oauth2/code/{registrationId}").scope("user").authorizationUri("https://provider.com/oauth2/authorize").tokenUri("https://provider.com/oauth2/token").userInfoUri("https://provider.com/oauth2/user").userNameAttributeName("id").clientName("client-1").build();
    this.registration2 = ClientRegistration.withRegistrationId("client2").clientId("client-2").clientSecret("secret").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).scope("read", "write").tokenUri("https://provider.com/oauth2/token").build();
    this.registration3 = TestClientRegistrations.password().registrationId("client3").build();
    // @formatter:on
    this.clientRegistrationRepository = new InMemoryClientRegistrationRepository(this.registration1, this.registration2, this.registration3);
    this.authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
    OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder().authorizationCode().refreshToken().clientCredentials().build();
    DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(this.clientRegistrationRepository, this.authorizedClientRepository);
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
    this.argumentResolver = new OAuth2AuthorizedClientArgumentResolver(authorizedClientManager);
    this.authorizedClient1 = new OAuth2AuthorizedClient(this.registration1, this.principalName, mock(OAuth2AccessToken.class));
    given(this.authorizedClientRepository.loadAuthorizedClient(eq(this.registration1.getRegistrationId()), any(Authentication.class), any(HttpServletRequest.class))).willReturn(this.authorizedClient1);
    this.authorizedClient2 = new OAuth2AuthorizedClient(this.registration2, this.principalName, mock(OAuth2AccessToken.class));
    given(this.authorizedClientRepository.loadAuthorizedClient(eq(this.registration2.getRegistrationId()), any(Authentication.class), any(HttpServletRequest.class))).willReturn(this.authorizedClient2);
    this.request = new MockHttpServletRequest();
    this.response = new MockHttpServletResponse();
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) Authentication(org.springframework.security.core.Authentication) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) SecurityContext(org.springframework.security.core.context.SecurityContext) InMemoryClientRegistrationRepository(org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository) OAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider) PasswordOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.PasswordOAuth2AuthorizedClientProvider) ClientCredentialsOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.ClientCredentialsOAuth2AuthorizedClientProvider) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) DefaultOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) OAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 2 with InMemoryClientRegistrationRepository

use of org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository in project spring-security by spring-projects.

the class OAuth2LoginAuthenticationFilterTests method setUp.

@BeforeEach
public void setUp() {
    this.registration1 = TestClientRegistrations.clientRegistration().build();
    this.registration2 = TestClientRegistrations.clientRegistration2().build();
    this.clientRegistrationRepository = new InMemoryClientRegistrationRepository(this.registration1, this.registration2);
    this.authorizedClientService = new InMemoryOAuth2AuthorizedClientService(this.clientRegistrationRepository);
    this.authorizedClientRepository = new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(this.authorizedClientService);
    this.authorizationRequestRepository = new HttpSessionOAuth2AuthorizationRequestRepository();
    this.failureHandler = mock(AuthenticationFailureHandler.class);
    this.authenticationManager = mock(AuthenticationManager.class);
    this.authenticationDetailsSource = mock(AuthenticationDetailsSource.class);
    this.filter = spy(new OAuth2LoginAuthenticationFilter(this.clientRegistrationRepository, this.authorizedClientRepository, OAuth2LoginAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI));
    this.filter.setAuthorizationRequestRepository(this.authorizationRequestRepository);
    this.filter.setAuthenticationFailureHandler(this.failureHandler);
    this.filter.setAuthenticationManager(this.authenticationManager);
    this.filter.setAuthenticationDetailsSource(this.authenticationDetailsSource);
}
Also used : AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) AuthenticationDetailsSource(org.springframework.security.authentication.AuthenticationDetailsSource) InMemoryOAuth2AuthorizedClientService(org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService) InMemoryClientRegistrationRepository(org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository) AuthenticationFailureHandler(org.springframework.security.web.authentication.AuthenticationFailureHandler) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 3 with InMemoryClientRegistrationRepository

use of org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository in project spring-security by spring-projects.

the class OAuth2ClientConfigurerTests method setup.

@BeforeEach
public void setup() {
    // @formatter:off
    this.registration1 = TestClientRegistrations.clientRegistration().registrationId("registration-1").clientId("client-1").clientSecret("secret").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).redirectUri("{baseUrl}/client-1").scope("user").authorizationUri("https://provider.com/oauth2/authorize").tokenUri("https://provider.com/oauth2/token").userInfoUri("https://provider.com/oauth2/user").userNameAttributeName("id").clientName("client-1").build();
    // @formatter:on
    clientRegistrationRepository = new InMemoryClientRegistrationRepository(this.registration1);
    authorizedClientService = new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository);
    authorizedClientRepository = new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(authorizedClientService);
    authorizationRequestResolver = new DefaultOAuth2AuthorizationRequestResolver(clientRegistrationRepository, "/oauth2/authorization");
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(300).build();
    accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
    given(accessTokenResponseClient.getTokenResponse(any(OAuth2AuthorizationCodeGrantRequest.class))).willReturn(accessTokenResponse);
    requestCache = mock(RequestCache.class);
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) RequestCache(org.springframework.security.web.savedrequest.RequestCache) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) InMemoryOAuth2AuthorizedClientService(org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService) InMemoryClientRegistrationRepository(org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository) AuthenticatedPrincipalOAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAuth2AuthorizedClientRepository) OAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient) DefaultOAuth2AuthorizationRequestResolver(org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizationRequestResolver) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 4 with InMemoryClientRegistrationRepository

use of org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository in project spring-security by spring-projects.

the class OAuth2AuthorizationRequestRedirectFilterTests method setUp.

@BeforeEach
public void setUp() {
    this.registration1 = TestClientRegistrations.clientRegistration().build();
    this.registration2 = TestClientRegistrations.clientRegistration2().build();
    // @formatter:off
    this.registration3 = TestClientRegistrations.clientRegistration().registrationId("registration-3").authorizationGrantType(AuthorizationGrantType.IMPLICIT).redirectUri("{baseUrl}/authorize/oauth2/implicit/{registrationId}").build();
    // @formatter:on
    this.clientRegistrationRepository = new InMemoryClientRegistrationRepository(this.registration1, this.registration2, this.registration3);
    this.filter = new OAuth2AuthorizationRequestRedirectFilter(this.clientRegistrationRepository);
    this.requestCache = mock(RequestCache.class);
    this.filter.setRequestCache(this.requestCache);
}
Also used : RequestCache(org.springframework.security.web.savedrequest.RequestCache) InMemoryClientRegistrationRepository(org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 5 with InMemoryClientRegistrationRepository

use of org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository in project midpoint by Evolveum.

the class OidcClientModuleWebSecurityConfiguration method buildInternal.

private static OidcClientModuleWebSecurityConfiguration buildInternal(OidcAuthenticationModuleType modelType, String prefixOfSequence, String publicHttpUrlPattern, ServletRequest request) {
    OidcClientModuleWebSecurityConfiguration configuration = new OidcClientModuleWebSecurityConfiguration();
    build(configuration, modelType, prefixOfSequence);
    List<OidcClientAuthenticationModuleType> clients = modelType.getClient();
    List<ClientRegistration> registrations = new ArrayList<>();
    clients.forEach(client -> {
        OidcOpenIdProviderType openIdProvider = client.getOpenIdProvider();
        Assert.notNull(openIdProvider, "openIdProvider cannot be null");
        ClientRegistration.Builder builder = null;
        try {
            builder = ClientRegistrations.fromOidcIssuerLocation(openIdProvider.getIssuerUri());
        } catch (Exception e) {
            LOGGER.debug("Couldn't create oidc client builder by issuer uri.");
        }
        Assert.hasText(client.getRegistrationId(), "registrationId cannot be empty");
        if (builder == null) {
            builder = ClientRegistration.withRegistrationId(client.getRegistrationId());
        } else {
            builder.registrationId(client.getRegistrationId());
        }
        builder.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE);
        builder.userInfoAuthenticationMethod(AuthenticationMethod.HEADER);
        UriComponentsBuilder redirectUri = UriComponentsBuilder.fromUriString(StringUtils.isNotBlank(publicHttpUrlPattern) ? publicHttpUrlPattern : getBasePath((HttpServletRequest) request));
        redirectUri.pathSegment(DEFAULT_PREFIX_OF_MODULE, AuthUtil.stripSlashes(prefixOfSequence), AuthUtil.stripSlashes(modelType.getName()), AuthUtil.stripSlashes(RemoteModuleAuthenticationImpl.AUTHENTICATION_REQUEST_PROCESSING_URL_SUFFIX), client.getRegistrationId());
        builder.redirectUri(redirectUri.toUriString());
        Assert.hasText(client.getClientId(), "clientId cannot be empty");
        builder.clientId(client.getClientId());
        if (client.getNameOfUsernameAttribute() != null) {
            builder.userNameAttributeName(client.getNameOfUsernameAttribute());
        }
        if (!Objects.isNull(client.getClientSecret())) {
            try {
                String clientSecret = protector.decryptString(client.getClientSecret());
                builder.clientSecret(clientSecret);
            } catch (EncryptionException e) {
                LOGGER.error("Couldn't obtain clear string for client secret");
            }
        }
        getOptionalIfNotEmpty(client.getClientName()).ifPresent(builder::clientName);
        getOptionalIfNotEmpty(openIdProvider.getAuthorizationUri()).ifPresent(builder::authorizationUri);
        getOptionalIfNotEmpty(openIdProvider.getTokenUri()).ifPresent(builder::tokenUri);
        getOptionalIfNotEmpty(openIdProvider.getUserInfoUri()).ifPresent(builder::userInfoUri);
        getOptionalIfNotEmpty(openIdProvider.getIssuerUri()).ifPresent(builder::issuerUri);
        ClientRegistration clientRegistration = builder.build();
        if (clientRegistration.getScopes() == null || !clientRegistration.getScopes().contains("openid")) {
            List<String> scopes = new ArrayList<>();
            if (clientRegistration.getScopes() != null) {
                scopes.addAll(clientRegistration.getScopes());
            }
            scopes.add("openid");
            builder.scope(scopes);
        }
        if (StringUtils.isNotEmpty(openIdProvider.getEndSessionUri())) {
            Map<String, Object> configurationMetadata = new HashMap<>(clientRegistration.getProviderDetails().getConfigurationMetadata());
            configurationMetadata.remove("end_session_endpoint");
            configurationMetadata.put("end_session_endpoint", openIdProvider.getEndSessionUri());
            builder.providerConfigurationMetadata(configurationMetadata);
        }
        if (client.getClientAuthenticationMethod() != null) {
            builder.clientAuthenticationMethod(new ClientAuthenticationMethod(client.getClientAuthenticationMethod().name().toLowerCase()));
        }
        clientRegistration = builder.build();
        Assert.hasText(clientRegistration.getProviderDetails().getUserInfoEndpoint().getUri(), "UserInfoUri cannot be empty");
        registrations.add(clientRegistration);
        OidcAdditionalConfiguration.Builder additionalConfBuilder = OidcAdditionalConfiguration.builder().singingAlg(client.getClientSigningAlgorithm());
        if (client.getSimpleProofKey() != null) {
            initializeProofKey(client.getSimpleProofKey(), additionalConfBuilder);
        } else if (client.getKeyStoreProofKey() != null) {
            initializeProofKey(client.getKeyStoreProofKey(), additionalConfBuilder);
        }
        configuration.additionalConfiguration.put(client.getRegistrationId(), additionalConfBuilder.build());
    });
    configuration.clientRegistrationRepository = new InMemoryClientRegistrationRepository(registrations);
    return configuration;
}
Also used : InMemoryClientRegistrationRepository(org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) Base64Exception(org.apache.cxf.common.util.Base64Exception) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException)

Aggregations

InMemoryClientRegistrationRepository (org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository)8 BeforeEach (org.junit.jupiter.api.BeforeEach)6 InMemoryOAuth2AuthorizedClientService (org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService)3 AuthenticationManager (org.springframework.security.authentication.AuthenticationManager)2 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)2 SecurityContext (org.springframework.security.core.context.SecurityContext)2 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)2 RequestCache (org.springframework.security.web.savedrequest.RequestCache)2 EncryptionException (com.evolveum.midpoint.prism.crypto.EncryptionException)1 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)1 IOException (java.io.IOException)1 CertificateException (java.security.cert.CertificateException)1 Base64Exception (org.apache.cxf.common.util.Base64Exception)1 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)1 PKCSException (org.bouncycastle.pkcs.PKCSException)1 Test (org.junit.jupiter.api.Test)1 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)1 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)1 AuthenticationDetailsSource (org.springframework.security.authentication.AuthenticationDetailsSource)1 Authentication (org.springframework.security.core.Authentication)1