Search in sources :

Example 11 with OAuth2AuthorizationCodeGrantRequest

use of org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest in project spring-security by spring-projects.

the class DefaultAuthorizationCodeTokenResponseClientTests method authorizationCodeGrantRequest.

private OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest(ClientRegistration clientRegistration) {
    OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode().clientId(clientRegistration.getClientId()).state("state-1234").authorizationUri(clientRegistration.getProviderDetails().getAuthorizationUri()).redirectUri(clientRegistration.getRedirectUri()).scopes(clientRegistration.getScopes()).build();
    OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponse.success("code-1234").state("state-1234").redirectUri(clientRegistration.getRedirectUri()).build();
    OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse);
    return new OAuth2AuthorizationCodeGrantRequest(clientRegistration, authorizationExchange);
}
Also used : OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)

Example 12 with OAuth2AuthorizationCodeGrantRequest

use of org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest in project spring-security by spring-projects.

the class OAuth2LoginConfigurer method init.

@Override
public void init(B http) throws Exception {
    OAuth2LoginAuthenticationFilter authenticationFilter = new OAuth2LoginAuthenticationFilter(OAuth2ClientConfigurerUtils.getClientRegistrationRepository(this.getBuilder()), OAuth2ClientConfigurerUtils.getAuthorizedClientRepository(this.getBuilder()), this.loginProcessingUrl);
    this.setAuthenticationFilter(authenticationFilter);
    super.loginProcessingUrl(this.loginProcessingUrl);
    if (this.loginPage != null) {
        // Set custom login page
        super.loginPage(this.loginPage);
        super.init(http);
    } else {
        Map<String, String> loginUrlToClientName = this.getLoginLinks();
        if (loginUrlToClientName.size() == 1) {
            // Setup auto-redirect to provider login page
            // when only 1 client is configured
            this.updateAuthenticationDefaults();
            this.updateAccessDefaults(http);
            String providerLoginPage = loginUrlToClientName.keySet().iterator().next();
            this.registerAuthenticationEntryPoint(http, this.getLoginEntryPoint(http, providerLoginPage));
        } else {
            super.init(http);
        }
    }
    OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient = this.tokenEndpointConfig.accessTokenResponseClient;
    if (accessTokenResponseClient == null) {
        accessTokenResponseClient = new DefaultAuthorizationCodeTokenResponseClient();
    }
    OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService = getOAuth2UserService();
    OAuth2LoginAuthenticationProvider oauth2LoginAuthenticationProvider = new OAuth2LoginAuthenticationProvider(accessTokenResponseClient, oauth2UserService);
    GrantedAuthoritiesMapper userAuthoritiesMapper = this.getGrantedAuthoritiesMapper();
    if (userAuthoritiesMapper != null) {
        oauth2LoginAuthenticationProvider.setAuthoritiesMapper(userAuthoritiesMapper);
    }
    http.authenticationProvider(this.postProcess(oauth2LoginAuthenticationProvider));
    boolean oidcAuthenticationProviderEnabled = ClassUtils.isPresent("org.springframework.security.oauth2.jwt.JwtDecoder", this.getClass().getClassLoader());
    if (oidcAuthenticationProviderEnabled) {
        OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService = getOidcUserService();
        OidcAuthorizationCodeAuthenticationProvider oidcAuthorizationCodeAuthenticationProvider = new OidcAuthorizationCodeAuthenticationProvider(accessTokenResponseClient, oidcUserService);
        JwtDecoderFactory<ClientRegistration> jwtDecoderFactory = this.getJwtDecoderFactoryBean();
        if (jwtDecoderFactory != null) {
            oidcAuthorizationCodeAuthenticationProvider.setJwtDecoderFactory(jwtDecoderFactory);
        }
        if (userAuthoritiesMapper != null) {
            oidcAuthorizationCodeAuthenticationProvider.setAuthoritiesMapper(userAuthoritiesMapper);
        }
        http.authenticationProvider(this.postProcess(oidcAuthorizationCodeAuthenticationProvider));
    } else {
        http.authenticationProvider(new OidcAuthenticationRequestChecker());
    }
    this.initDefaultLoginFilter(http);
}
Also used : OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) OAuth2UserRequest(org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest) OidcAuthorizationCodeAuthenticationProvider(org.springframework.security.oauth2.client.oidc.authentication.OidcAuthorizationCodeAuthenticationProvider) GrantedAuthoritiesMapper(org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2LoginAuthenticationFilter(org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter) DefaultAuthorizationCodeTokenResponseClient(org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient) OAuth2LoginAuthenticationProvider(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationProvider)

Example 13 with OAuth2AuthorizationCodeGrantRequest

use of org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest in project spring-security by spring-projects.

the class OAuth2LoginTests method oauth2LoginWhenCustomBeansThenUsed.

@Test
public void oauth2LoginWhenCustomBeansThenUsed() {
    this.spring.register(OAuth2LoginWithMultipleClientRegistrations.class, OAuth2LoginWithCustomBeansConfig.class).autowire();
    // @formatter:off
    WebTestClient webTestClient = WebTestClientBuilder.bindToWebFilters(this.springSecurity).build();
    // @formatter:on
    OAuth2LoginWithCustomBeansConfig config = this.spring.getContext().getBean(OAuth2LoginWithCustomBeansConfig.class);
    OAuth2AuthorizationRequest request = TestOAuth2AuthorizationRequests.request().scope("openid").build();
    OAuth2AuthorizationResponse response = TestOAuth2AuthorizationResponses.success().build();
    OAuth2AuthorizationExchange exchange = new OAuth2AuthorizationExchange(request, response);
    OAuth2AccessToken accessToken = TestOAuth2AccessTokens.scopes("openid");
    OAuth2AuthorizationCodeAuthenticationToken token = new OAuth2AuthorizationCodeAuthenticationToken(google, exchange, accessToken);
    ServerAuthenticationConverter converter = config.authenticationConverter;
    given(converter.convert(any())).willReturn(Mono.just(token));
    ServerSecurityContextRepository securityContextRepository = config.securityContextRepository;
    given(securityContextRepository.save(any(), any())).willReturn(Mono.empty());
    given(securityContextRepository.load(any())).willReturn(authentication(token));
    Map<String, Object> additionalParameters = new HashMap<>();
    additionalParameters.put(OidcParameterNames.ID_TOKEN, "id-token");
    // @formatter:off
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken(accessToken.getTokenValue()).tokenType(accessToken.getTokenType()).scopes(accessToken.getScopes()).additionalParameters(additionalParameters).build();
    // @formatter:on
    ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> tokenResponseClient = config.tokenResponseClient;
    given(tokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    OidcUser user = TestOidcUsers.create();
    ReactiveOAuth2UserService<OidcUserRequest, OidcUser> userService = config.userService;
    given(userService.loadUser(any())).willReturn(Mono.just(user));
    // @formatter:off
    webTestClient.get().uri("/login/oauth2/code/google").exchange().expectStatus().is3xxRedirection();
    // @formatter:on
    verify(config.jwtDecoderFactory).createDecoder(any());
    verify(tokenResponseClient).getTokenResponse(any());
    verify(securityContextRepository).save(any(), any());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) HashMap(java.util.HashMap) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) ServerAuthenticationConverter(org.springframework.security.web.server.authentication.ServerAuthenticationConverter) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) ServerSecurityContextRepository(org.springframework.security.web.server.context.ServerSecurityContextRepository) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 14 with OAuth2AuthorizationCodeGrantRequest

use of org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest in project spring-security by spring-projects.

the class OAuth2LoginTests method oauth2LoginWhenAccessTokenRequestFailsThenDefaultRedirectToLogin.

// gh-5562
@Test
public void oauth2LoginWhenAccessTokenRequestFailsThenDefaultRedirectToLogin() {
    this.spring.register(OAuth2LoginWithMultipleClientRegistrations.class, OAuth2LoginWithCustomBeansConfig.class).autowire();
    // @formatter:off
    WebTestClient webTestClient = WebTestClientBuilder.bindToWebFilters(this.springSecurity).build();
    OAuth2AuthorizationRequest request = TestOAuth2AuthorizationRequests.request().scope("openid").build();
    // @formatter:on
    OAuth2AuthorizationResponse response = TestOAuth2AuthorizationResponses.success().build();
    OAuth2AuthorizationExchange exchange = new OAuth2AuthorizationExchange(request, response);
    OAuth2AccessToken accessToken = TestOAuth2AccessTokens.scopes("openid");
    OAuth2AuthorizationCodeAuthenticationToken authenticationToken = new OAuth2AuthorizationCodeAuthenticationToken(google, exchange, accessToken);
    OAuth2LoginWithCustomBeansConfig config = this.spring.getContext().getBean(OAuth2LoginWithCustomBeansConfig.class);
    ServerAuthenticationConverter converter = config.authenticationConverter;
    given(converter.convert(any())).willReturn(Mono.just(authenticationToken));
    ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> tokenResponseClient = config.tokenResponseClient;
    OAuth2Error oauth2Error = new OAuth2Error("invalid_request", "Invalid request", null);
    given(tokenResponseClient.getTokenResponse(any())).willThrow(new OAuth2AuthenticationException(oauth2Error));
    // @formatter:off
    webTestClient.get().uri("/login/oauth2/code/google").exchange().expectStatus().is3xxRedirection().expectHeader().valueEquals("Location", "/login?error");
// @formatter:on
}
Also used : WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) ServerAuthenticationConverter(org.springframework.security.web.server.authentication.ServerAuthenticationConverter) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 15 with OAuth2AuthorizationCodeGrantRequest

use of org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest in project spring-security by spring-projects.

the class OAuth2AuthorizationCodeGrantRequestEntityConverterTests method convertWhenGrantRequestValidThenConverts.

@SuppressWarnings("unchecked")
@Test
public void convertWhenGrantRequestValidThenConverts() {
    ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
    OAuth2AuthorizationExchange authorizationExchange = TestOAuth2AuthorizationExchanges.success();
    OAuth2AuthorizationRequest authorizationRequest = authorizationExchange.getAuthorizationRequest();
    OAuth2AuthorizationResponse authorizationResponse = authorizationExchange.getAuthorizationResponse();
    OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest = new OAuth2AuthorizationCodeGrantRequest(clientRegistration, authorizationExchange);
    RequestEntity<?> requestEntity = this.converter.convert(authorizationCodeGrantRequest);
    assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.POST);
    assertThat(requestEntity.getUrl().toASCIIString()).isEqualTo(clientRegistration.getProviderDetails().getTokenUri());
    HttpHeaders headers = requestEntity.getHeaders();
    assertThat(headers.getAccept()).contains(MediaType.APPLICATION_JSON_UTF8);
    assertThat(headers.getContentType()).isEqualTo(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"));
    assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
    MultiValueMap<String, String> formParameters = (MultiValueMap<String, String>) requestEntity.getBody();
    assertThat(formParameters.getFirst(OAuth2ParameterNames.GRANT_TYPE)).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE.getValue());
    assertThat(formParameters.getFirst(OAuth2ParameterNames.CODE)).isEqualTo(authorizationResponse.getCode());
    assertThat(formParameters.getFirst(OAuth2ParameterNames.CLIENT_ID)).isNull();
    assertThat(formParameters.getFirst(OAuth2ParameterNames.REDIRECT_URI)).isEqualTo(authorizationRequest.getRedirectUri());
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) MultiValueMap(org.springframework.util.MultiValueMap) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2AuthorizationExchange (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange)15 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)14 Test (org.junit.jupiter.api.Test)12 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)12 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)11 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)9 OAuth2AuthorizationCodeGrantRequest (org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest)7 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)5 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)5 HashMap (java.util.HashMap)4 HttpHeaders (org.springframework.http.HttpHeaders)4 OAuth2AuthorizationCodeAuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken)4 OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)4 MockResponse (okhttp3.mockwebserver.MockResponse)3 MockWebServer (okhttp3.mockwebserver.MockWebServer)3 OidcUserRequest (org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest)3 OidcUser (org.springframework.security.oauth2.core.oidc.user.OidcUser)3 ServerAuthenticationConverter (org.springframework.security.web.server.authentication.ServerAuthenticationConverter)3 WebTestClient (org.springframework.test.web.reactive.server.WebTestClient)3 GrantedAuthoritiesMapper (org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper)2