Search in sources :

Example 71 with OAuth2AuthorizationRequest

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

the class Oauth2AuthenticationSuccessHandler method onAuthenticationSuccess.

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
    OAuth2AuthorizationRequest authorizationRequest = httpCookieOAuth2AuthorizationRequestRepository.loadAuthorizationRequest(request);
    String callbackUrlScheme = authorizationRequest.getAttribute(TbOAuth2ParameterNames.CALLBACK_URL_SCHEME);
    String baseUrl;
    if (!StringUtils.isEmpty(callbackUrlScheme)) {
        baseUrl = callbackUrlScheme + ":";
    } else {
        baseUrl = this.systemSecurityService.getBaseUrl(TenantId.SYS_TENANT_ID, new CustomerId(EntityId.NULL_UUID), request);
    }
    try {
        OAuth2AuthenticationToken token = (OAuth2AuthenticationToken) authentication;
        OAuth2Registration registration = oAuth2Service.findRegistration(UUID.fromString(token.getAuthorizedClientRegistrationId()));
        OAuth2AuthorizedClient oAuth2AuthorizedClient = oAuth2AuthorizedClientService.loadAuthorizedClient(token.getAuthorizedClientRegistrationId(), token.getPrincipal().getName());
        OAuth2ClientMapper mapper = oauth2ClientMapperProvider.getOAuth2ClientMapperByType(registration.getMapperConfig().getType());
        SecurityUser securityUser = mapper.getOrCreateUserByClientPrincipal(request, token, oAuth2AuthorizedClient.getAccessToken().getTokenValue(), registration);
        JwtToken accessToken = tokenFactory.createAccessJwtToken(securityUser);
        JwtToken refreshToken = refreshTokenRepository.requestRefreshToken(securityUser);
        clearAuthenticationAttributes(request, response);
        getRedirectStrategy().sendRedirect(request, response, baseUrl + "/?accessToken=" + accessToken.getToken() + "&refreshToken=" + refreshToken.getToken());
    } catch (Exception e) {
        log.debug("Error occurred during processing authentication success result. " + "request [{}], response [{}], authentication [{}]", request, response, authentication, e);
        clearAuthenticationAttributes(request, response);
        String errorPrefix;
        if (!StringUtils.isEmpty(callbackUrlScheme)) {
            errorPrefix = "/?error=";
        } else {
            errorPrefix = "/login?loginError=";
        }
        getRedirectStrategy().sendRedirect(request, response, baseUrl + errorPrefix + URLEncoder.encode(e.getMessage(), StandardCharsets.UTF_8.toString()));
    }
}
Also used : JwtToken(org.thingsboard.server.common.data.security.model.JwtToken) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) OAuth2Registration(org.thingsboard.server.common.data.oauth2.OAuth2Registration) CustomerId(org.thingsboard.server.common.data.id.CustomerId) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) IOException(java.io.IOException)

Example 72 with OAuth2AuthorizationRequest

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

the class OAuth2LoginConfigurerTests method oauth2Login.

@Test
public void oauth2Login() throws Exception {
    // setup application context
    loadConfig(OAuth2LoginConfig.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(1);
    assertThat(authentication.getAuthorities()).first().isInstanceOf(OAuth2UserAuthority.class).hasToString("ROLE_USER");
}
Also used : HttpRequestResponseHolder(org.springframework.security.web.context.HttpRequestResponseHolder) Authentication(org.springframework.security.core.Authentication) OAuth2UserAuthority(org.springframework.security.oauth2.core.user.OAuth2UserAuthority) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 73 with OAuth2AuthorizationRequest

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

the class OAuth2LoginConfigurerTests method oidcLoginCustomWithBeanRegistration.

@Test
public void oidcLoginCustomWithBeanRegistration() throws Exception {
    // setup application context
    loadConfig(OAuth2LoginConfigCustomWithBeanRegistration.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(2);
    assertThat(authentication.getAuthorities()).first().hasToString("ROLE_USER");
    assertThat(authentication.getAuthorities()).last().hasToString("ROLE_OIDC_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 74 with OAuth2AuthorizationRequest

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

the class OAuth2LoginConfigurerTests method oauth2LoginConfigLoginProcessingUrl.

// gh-5488
@Test
public void oauth2LoginConfigLoginProcessingUrl() throws Exception {
    // setup application context
    loadConfig(OAuth2LoginConfigLoginProcessingUrl.class);
    // setup authorization request
    OAuth2AuthorizationRequest authorizationRequest = createOAuth2AuthorizationRequest();
    this.request.setServletPath("/login/oauth2/google");
    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(OAuth2UserAuthority.class).hasToString("ROLE_USER");
}
Also used : HttpRequestResponseHolder(org.springframework.security.web.context.HttpRequestResponseHolder) Authentication(org.springframework.security.core.Authentication) OAuth2UserAuthority(org.springframework.security.oauth2.core.user.OAuth2UserAuthority) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 75 with OAuth2AuthorizationRequest

use of org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest 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)

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