Search in sources :

Example 1 with OAuth2AuthorizationRequest

use of org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest in project books by aidanwhiteley.

the class HttpCookieOAuth2AuthorizationRequestRepositoryTest method testSaveAndLoadCookie.

@Test
public void testSaveAndLoadCookie() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    String TEST_CLIENT_ID = "Hello world";
    String DUMMY_TEXT_NOT_TESTED = "dummy";
    OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode().clientId(TEST_CLIENT_ID).authorizationUri(DUMMY_TEXT_NOT_TESTED).build();
    HttpCookieOAuth2AuthorizationRequestRepository repo = new HttpCookieOAuth2AuthorizationRequestRepository();
    repo.saveAuthorizationRequest(authorizationRequest, request, response);
    // Now get the cookie that should have been added to the response
    Cookie cookie = response.getCookie(HttpCookieOAuth2AuthorizationRequestRepository.COOKIE_NAME);
    request.setCookies(cookie);
    OAuth2AuthorizationRequest retrievedOauth = repo.loadAuthorizationRequest(request);
    String clientId = retrievedOauth.getClientId();
    assertEquals(TEST_CLIENT_ID, clientId);
}
Also used : Cookie(javax.servlet.http.Cookie) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.Test)

Example 2 with OAuth2AuthorizationRequest

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

the class OAuth2LoginConfigurerTests method oidcLogin.

@Test
public void oidcLogin() throws Exception {
    // setup application context
    loadConfig(OAuth2LoginConfig.class, JwtDecoderFactoryConfig.class);
    // setup authorization request
    OAuth2AuthorizationRequest authorizationRequest = createOAuth2AuthorizationRequest("openid");
    this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, this.request, this.response);
    // setup authentication parameters
    this.request.setParameter("code", "code123");
    this.request.setParameter("state", authorizationRequest.getState());
    // perform test
    this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
    // assertions
    Authentication authentication = this.securityContextRepository.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
    assertThat(authentication.getAuthorities()).hasSize(1);
    assertThat(authentication.getAuthorities()).first().isInstanceOf(OidcUserAuthority.class).hasToString("ROLE_USER");
}
Also used : HttpRequestResponseHolder(org.springframework.security.web.context.HttpRequestResponseHolder) OidcUserAuthority(org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority) Authentication(org.springframework.security.core.Authentication) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 3 with OAuth2AuthorizationRequest

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

the class OAuth2LoginConfigurerTests method oauth2LoginCustomWithUserServiceBeanRegistration.

@Test
public void oauth2LoginCustomWithUserServiceBeanRegistration() throws Exception {
    // setup application context
    loadConfig(OAuth2LoginConfigCustomUserServiceBeanRegistration.class);
    // setup authorization request
    OAuth2AuthorizationRequest authorizationRequest = createOAuth2AuthorizationRequest();
    this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, this.request, this.response);
    // setup authentication parameters
    this.request.setParameter("code", "code123");
    this.request.setParameter("state", authorizationRequest.getState());
    // perform test
    this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
    // assertions
    Authentication authentication = this.securityContextRepository.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
    assertThat(authentication.getAuthorities()).hasSize(2);
    assertThat(authentication.getAuthorities()).first().hasToString("ROLE_USER");
    assertThat(authentication.getAuthorities()).last().hasToString("ROLE_OAUTH2_USER");
}
Also used : HttpRequestResponseHolder(org.springframework.security.web.context.HttpRequestResponseHolder) Authentication(org.springframework.security.core.Authentication) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 4 with OAuth2AuthorizationRequest

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

the class OAuth2ClientBeanDefinitionParserTests method requestWhenAuthorizationResponseMatchThenProcess.

@Test
public void requestWhenAuthorizationResponseMatchThenProcess() throws Exception {
    this.spring.configLocations(xml("CustomConfiguration")).autowire();
    ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("google");
    OAuth2AuthorizationRequest authorizationRequest = createAuthorizationRequest(clientRegistration);
    given(this.authorizationRequestRepository.loadAuthorizationRequest(any())).willReturn(authorizationRequest);
    given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any())).willReturn(authorizationRequest);
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("code", "code123");
    params.add("state", authorizationRequest.getState());
    // @formatter:off
    this.mvc.perform(get(authorizationRequest.getRedirectUri()).params(params)).andExpect(status().is3xxRedirection()).andExpect(redirectedUrl(authorizationRequest.getRedirectUri()));
    // @formatter:on
    ArgumentCaptor<OAuth2AuthorizedClient> authorizedClientCaptor = ArgumentCaptor.forClass(OAuth2AuthorizedClient.class);
    verify(this.authorizedClientRepository).saveAuthorizedClient(authorizedClientCaptor.capture(), any(), any(), any());
    OAuth2AuthorizedClient authorizedClient = authorizedClientCaptor.getValue();
    assertThat(authorizedClient.getClientRegistration()).isEqualTo(clientRegistration);
    assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 5 with OAuth2AuthorizationRequest

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

the class OidcAuthorizationCodeAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    OAuth2LoginAuthenticationToken authorizationCodeAuthentication = (OAuth2LoginAuthenticationToken) authentication;
    // REQUIRED. OpenID Connect requests MUST contain the "openid" scope value.
    if (!authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationRequest().getScopes().contains(OidcScopes.OPENID)) {
        // and let OAuth2LoginAuthenticationProvider handle it instead
        return null;
    }
    OAuth2AuthorizationRequest authorizationRequest = authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationRequest();
    OAuth2AuthorizationResponse authorizationResponse = authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationResponse();
    if (authorizationResponse.statusError()) {
        throw new OAuth2AuthenticationException(authorizationResponse.getError(), authorizationResponse.getError().toString());
    }
    if (!authorizationResponse.getState().equals(authorizationRequest.getState())) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_STATE_PARAMETER_ERROR_CODE);
        throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
    }
    OAuth2AccessTokenResponse accessTokenResponse = getResponse(authorizationCodeAuthentication);
    ClientRegistration clientRegistration = authorizationCodeAuthentication.getClientRegistration();
    Map<String, Object> additionalParameters = accessTokenResponse.getAdditionalParameters();
    if (!additionalParameters.containsKey(OidcParameterNames.ID_TOKEN)) {
        OAuth2Error invalidIdTokenError = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE, "Missing (required) ID Token in Token Response for Client Registration: " + clientRegistration.getRegistrationId(), null);
        throw new OAuth2AuthenticationException(invalidIdTokenError, invalidIdTokenError.toString());
    }
    OidcIdToken idToken = createOidcToken(clientRegistration, accessTokenResponse);
    validateNonce(authorizationRequest, idToken);
    OidcUser oidcUser = this.userService.loadUser(new OidcUserRequest(clientRegistration, accessTokenResponse.getAccessToken(), idToken, additionalParameters));
    Collection<? extends GrantedAuthority> mappedAuthorities = this.authoritiesMapper.mapAuthorities(oidcUser.getAuthorities());
    OAuth2LoginAuthenticationToken authenticationResult = new OAuth2LoginAuthenticationToken(authorizationCodeAuthentication.getClientRegistration(), authorizationCodeAuthentication.getAuthorizationExchange(), oidcUser, mappedAuthorities, accessTokenResponse.getAccessToken(), accessTokenResponse.getRefreshToken());
    authenticationResult.setDetails(authorizationCodeAuthentication.getDetails());
    return authenticationResult;
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) OidcIdToken(org.springframework.security.oauth2.core.oidc.OidcIdToken) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)

Aggregations

OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)134 Test (org.junit.jupiter.api.Test)111 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)51 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)49 HashMap (java.util.HashMap)25 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