Search in sources :

Example 21 with OAuth2AuthorizationRequest

use of org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest in project spring-security by spring-projects.

the class OAuth2LoginBeanDefinitionParserTests method requestWhenAuthorizationResponseValidThenAuthenticate.

@Test
public void requestWhenAuthorizationResponseValidThenAuthenticate() throws Exception {
    this.spring.configLocations(this.xml("MultiClientRegistration-WithCustomConfiguration")).autowire();
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(OAuth2ParameterNames.REGISTRATION_ID, "github-login");
    OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request().attributes(attributes).build();
    given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any())).willReturn(authorizationRequest);
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    OAuth2User oauth2User = TestOAuth2Users.create();
    given(this.oauth2UserService.loadUser(any())).willReturn(oauth2User);
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("code", "code123");
    params.add("state", authorizationRequest.getState());
    // @formatter:off
    this.mvc.perform(get("/login/oauth2/code/github-login").params(params)).andExpect(status().is2xxSuccessful());
    // @formatter:on
    ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
    verify(this.authenticationSuccessHandler).onAuthenticationSuccess(any(), any(), authenticationCaptor.capture());
    Authentication authentication = authenticationCaptor.getValue();
    assertThat(authentication.getPrincipal()).isInstanceOf(OAuth2User.class);
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) HashMap(java.util.HashMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Authentication(org.springframework.security.core.Authentication) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 22 with OAuth2AuthorizationRequest

use of org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest in project spring-security by spring-projects.

the class OAuth2LoginBeanDefinitionParserTests method requestWhenOidcAuthenticationResponseValidThenJwtDecoderFactoryCalled.

@Test
public void requestWhenOidcAuthenticationResponseValidThenJwtDecoderFactoryCalled() throws Exception {
    this.spring.configLocations(this.xml("SingleClientRegistration-WithJwtDecoderFactoryAndDefaultSuccessHandler")).autowire();
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(OAuth2ParameterNames.REGISTRATION_ID, "google-login");
    OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.oidcRequest().attributes(attributes).build();
    given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any())).willReturn(authorizationRequest);
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.oidcAccessTokenResponse().build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    Jwt jwt = TestJwts.user();
    given(this.jwtDecoderFactory.createDecoder(any())).willReturn((token) -> jwt);
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("code", "code123");
    params.add("state", authorizationRequest.getState());
    // @formatter:off
    this.mvc.perform(get("/login/oauth2/code/google-login").params(params)).andExpect(status().is3xxRedirection()).andExpect(redirectedUrl("/"));
    // @formatter:on
    verify(this.jwtDecoderFactory).createDecoder(any());
    verify(this.requestCache).getRequest(any(), any());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) HashMap(java.util.HashMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Jwt(org.springframework.security.oauth2.jwt.Jwt) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 23 with OAuth2AuthorizationRequest

use of org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest in project spring-security by spring-projects.

the class HttpSessionOAuth2AuthorizationRequestRepository method removeAuthorizationRequest.

@Override
public OAuth2AuthorizationRequest removeAuthorizationRequest(HttpServletRequest request) {
    Assert.notNull(request, "request cannot be null");
    String stateParameter = this.getStateParameter(request);
    if (stateParameter == null) {
        return null;
    }
    Map<String, OAuth2AuthorizationRequest> authorizationRequests = this.getAuthorizationRequests(request);
    OAuth2AuthorizationRequest originalRequest = authorizationRequests.remove(stateParameter);
    if (authorizationRequests.size() == 0) {
        request.getSession().removeAttribute(this.sessionAttributeName);
    } else if (authorizationRequests.size() == 1) {
        request.getSession().setAttribute(this.sessionAttributeName, authorizationRequests.values().iterator().next());
    } else {
        request.getSession().setAttribute(this.sessionAttributeName, authorizationRequests);
    }
    return originalRequest;
}
Also used : OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)

Example 24 with OAuth2AuthorizationRequest

use of org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest in project spring-security by spring-projects.

the class HttpSessionOAuth2AuthorizationRequestRepository method getAuthorizationRequests.

/**
 * Gets a non-null and mutable map of {@link OAuth2AuthorizationRequest#getState()} to
 * an {@link OAuth2AuthorizationRequest}
 * @param request
 * @return a non-null and mutable map of {@link OAuth2AuthorizationRequest#getState()}
 * to an {@link OAuth2AuthorizationRequest}.
 */
private Map<String, OAuth2AuthorizationRequest> getAuthorizationRequests(HttpServletRequest request) {
    HttpSession session = request.getSession(false);
    Object sessionAttributeValue = (session != null) ? session.getAttribute(this.sessionAttributeName) : null;
    if (sessionAttributeValue == null) {
        return new HashMap<>();
    } else if (sessionAttributeValue instanceof OAuth2AuthorizationRequest) {
        OAuth2AuthorizationRequest auth2AuthorizationRequest = (OAuth2AuthorizationRequest) sessionAttributeValue;
        Map<String, OAuth2AuthorizationRequest> authorizationRequests = new HashMap<>(1);
        authorizationRequests.put(auth2AuthorizationRequest.getState(), auth2AuthorizationRequest);
        return authorizationRequests;
    } else if (sessionAttributeValue instanceof Map) {
        @SuppressWarnings("unchecked") Map<String, OAuth2AuthorizationRequest> authorizationRequests = (Map<String, OAuth2AuthorizationRequest>) sessionAttributeValue;
        return authorizationRequests;
    } else {
        throw new IllegalStateException("authorizationRequests is supposed to be a Map or OAuth2AuthorizationRequest but actually is a " + sessionAttributeValue.getClass());
    }
}
Also used : HashMap(java.util.HashMap) HttpSession(jakarta.servlet.http.HttpSession) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Map(java.util.Map) HashMap(java.util.HashMap)

Example 25 with OAuth2AuthorizationRequest

use of org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest in project spring-security by spring-projects.

the class OAuth2LoginTests method oauth2LoginWhenIdTokenValidationFailsThenDefaultRedirectToLogin.

// gh-6484
@Test
public void oauth2LoginWhenIdTokenValidationFailsThenDefaultRedirectToLogin() {
    this.spring.register(OAuth2LoginWithMultipleClientRegistrations.class, OAuth2LoginWithCustomBeansConfig.class).autowire();
    WebTestClient webTestClient = WebTestClientBuilder.bindToWebFilters(this.springSecurity).build();
    OAuth2LoginWithCustomBeansConfig config = this.spring.getContext().getBean(OAuth2LoginWithCustomBeansConfig.class);
    // @formatter:off
    OAuth2AuthorizationRequest request = TestOAuth2AuthorizationRequests.request().scope("openid").build();
    OAuth2AuthorizationResponse response = TestOAuth2AuthorizationResponses.success().build();
    // @formatter:on
    OAuth2AuthorizationExchange exchange = new OAuth2AuthorizationExchange(request, response);
    OAuth2AccessToken accessToken = TestOAuth2AccessTokens.scopes("openid");
    OAuth2AuthorizationCodeAuthenticationToken authenticationToken = new OAuth2AuthorizationCodeAuthenticationToken(google, exchange, accessToken);
    ServerAuthenticationConverter converter = config.authenticationConverter;
    given(converter.convert(any())).willReturn(Mono.just(authenticationToken));
    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));
    ReactiveJwtDecoderFactory<ClientRegistration> jwtDecoderFactory = config.jwtDecoderFactory;
    OAuth2Error oauth2Error = new OAuth2Error("invalid_id_token", "Invalid ID Token", null);
    given(jwtDecoderFactory.createDecoder(any())).willReturn((token) -> Mono.error(new JwtValidationException("ID Token validation failed", Collections.singleton(oauth2Error))));
    // @formatter:off
    webTestClient.get().uri("/login/oauth2/code/google").exchange().expectStatus().is3xxRedirection().expectHeader().valueEquals("Location", "/login?error");
// @formatter:on
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) JwtValidationException(org.springframework.security.oauth2.jwt.JwtValidationException) 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) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) ServerAuthenticationConverter(org.springframework.security.web.server.authentication.ServerAuthenticationConverter) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)137 Test (org.junit.jupiter.api.Test)112 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)52 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)49 HashMap (java.util.HashMap)26 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)25 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)24 OAuth2AuthorizationExchange (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange)22 Authentication (org.springframework.security.core.Authentication)19 MockServerHttpRequest (org.springframework.mock.http.server.reactive.MockServerHttpRequest)18 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)17 ServerWebExchange (org.springframework.web.server.ServerWebExchange)13 OAuth2ParameterNames (org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames)12 MockServerWebExchange (org.springframework.mock.web.server.MockServerWebExchange)11 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)11 BeforeEach (org.junit.jupiter.api.BeforeEach)10 HttpRequestResponseHolder (org.springframework.security.web.context.HttpRequestResponseHolder)10 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)10 Map (java.util.Map)9 Mono (reactor.core.publisher.Mono)9