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()));
}
}
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");
}
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");
}
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");
}
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());
}
Aggregations