Search in sources :

Example 46 with OAuth2AccessToken

use of org.springframework.security.oauth2.core.OAuth2AccessToken in project mots by motech-implementations.

the class CustomTokenServices method createAccessToken.

@Override
public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException {
    OAuth2AccessToken accessToken = super.createAccessToken(authentication);
    User user = getUserFromPrincipal(authentication.getUserAuthentication().getPrincipal());
    userLogService.createNewUserLog(user, accessToken.getExpiration());
    return accessToken;
}
Also used : User(org.motechproject.mots.domain.security.User) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken)

Example 47 with OAuth2AccessToken

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

the class OidcReactiveOAuth2UserService method loadUser.

@Override
public Mono<OidcUser> loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
    Assert.notNull(userRequest, "userRequest cannot be null");
    // @formatter:off
    return getUserInfo(userRequest).map((userInfo) -> new OidcUserAuthority(userRequest.getIdToken(), userInfo)).defaultIfEmpty(new OidcUserAuthority(userRequest.getIdToken(), null)).map((authority) -> {
        OidcUserInfo userInfo = authority.getUserInfo();
        Set<GrantedAuthority> authorities = new HashSet<>();
        authorities.add(authority);
        OAuth2AccessToken token = userRequest.getAccessToken();
        for (String scope : token.getScopes()) {
            authorities.add(new SimpleGrantedAuthority("SCOPE_" + scope));
        }
        String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName();
        if (StringUtils.hasText(userNameAttributeName)) {
            return new DefaultOidcUser(authorities, userRequest.getIdToken(), userInfo, userNameAttributeName);
        }
        return new DefaultOidcUser(authorities, userRequest.getIdToken(), userInfo);
    });
// @formatter:on
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) OidcUserAuthority(org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) OidcUserInfo(org.springframework.security.oauth2.core.oidc.OidcUserInfo) DefaultOidcUser(org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser) HashSet(java.util.HashSet)

Example 48 with OAuth2AccessToken

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

the class OAuth2LoginAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    OAuth2LoginAuthenticationToken loginAuthenticationToken = (OAuth2LoginAuthenticationToken) authentication;
    // REQUIRED. OpenID Connect requests MUST contain the "openid" scope value.
    if (loginAuthenticationToken.getAuthorizationExchange().getAuthorizationRequest().getScopes().contains("openid")) {
        // and let OidcAuthorizationCodeAuthenticationProvider handle it instead
        return null;
    }
    OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthenticationToken;
    try {
        authorizationCodeAuthenticationToken = (OAuth2AuthorizationCodeAuthenticationToken) this.authorizationCodeAuthenticationProvider.authenticate(new OAuth2AuthorizationCodeAuthenticationToken(loginAuthenticationToken.getClientRegistration(), loginAuthenticationToken.getAuthorizationExchange()));
    } catch (OAuth2AuthorizationException ex) {
        OAuth2Error oauth2Error = ex.getError();
        throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
    }
    OAuth2AccessToken accessToken = authorizationCodeAuthenticationToken.getAccessToken();
    Map<String, Object> additionalParameters = authorizationCodeAuthenticationToken.getAdditionalParameters();
    OAuth2User oauth2User = this.userService.loadUser(new OAuth2UserRequest(loginAuthenticationToken.getClientRegistration(), accessToken, additionalParameters));
    Collection<? extends GrantedAuthority> mappedAuthorities = this.authoritiesMapper.mapAuthorities(oauth2User.getAuthorities());
    OAuth2LoginAuthenticationToken authenticationResult = new OAuth2LoginAuthenticationToken(loginAuthenticationToken.getClientRegistration(), loginAuthenticationToken.getAuthorizationExchange(), oauth2User, mappedAuthorities, accessToken, authorizationCodeAuthenticationToken.getRefreshToken());
    authenticationResult.setDetails(loginAuthenticationToken.getDetails());
    return authenticationResult;
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2UserRequest(org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException)

Example 49 with OAuth2AccessToken

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

the class ServerOAuth2AuthorizedClientExchangeFilterFunctionITests method requestWhenAuthorizedButExpiredThenRefreshAndSendRequest.

@Test
public void requestWhenAuthorizedButExpiredThenRefreshAndSendRequest() {
    // @formatter:off
    String accessTokenResponse = "{\n" + "	\"access_token\": \"refreshed-access-token\",\n" + "   \"token_type\": \"bearer\",\n" + "   \"expires_in\": \"3600\"\n" + "}\n";
    String clientResponse = "{\n" + "	\"attribute1\": \"value1\",\n" + "	\"attribute2\": \"value2\"\n" + "}\n";
    // @formatter:on
    this.server.enqueue(jsonResponse(accessTokenResponse));
    this.server.enqueue(jsonResponse(clientResponse));
    ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().tokenUri(this.serverUrl).build();
    given(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration.getRegistrationId()))).willReturn(Mono.just(clientRegistration));
    Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
    Instant expiresAt = issuedAt.plus(Duration.ofHours(1));
    OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "expired-access-token", issuedAt, expiresAt, new HashSet<>(Arrays.asList("read", "write")));
    OAuth2RefreshToken refreshToken = TestOAuth2RefreshTokens.refreshToken();
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, this.authentication.getName(), accessToken, refreshToken);
    doReturn(Mono.just(authorizedClient)).when(this.authorizedClientRepository).loadAuthorizedClient(eq(clientRegistration.getRegistrationId()), eq(this.authentication), eq(this.exchange));
    this.webClient.get().uri(this.serverUrl).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId(clientRegistration.getRegistrationId())).retrieve().bodyToMono(String.class).subscriberContext(Context.of(ServerWebExchange.class, this.exchange)).subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication)).block();
    assertThat(this.server.getRequestCount()).isEqualTo(2);
    ArgumentCaptor<OAuth2AuthorizedClient> authorizedClientCaptor = ArgumentCaptor.forClass(OAuth2AuthorizedClient.class);
    verify(this.authorizedClientRepository).saveAuthorizedClient(authorizedClientCaptor.capture(), eq(this.authentication), eq(this.exchange));
    OAuth2AuthorizedClient refreshedAuthorizedClient = authorizedClientCaptor.getValue();
    assertThat(refreshedAuthorizedClient.getClientRegistration()).isSameAs(clientRegistration);
    assertThat(refreshedAuthorizedClient.getAccessToken().getTokenValue()).isEqualTo("refreshed-access-token");
}
Also used : ServerWebExchange(org.springframework.web.server.ServerWebExchange) MockServerWebExchange(org.springframework.mock.web.server.MockServerWebExchange) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) Instant(java.time.Instant) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) Test(org.junit.jupiter.api.Test)

Example 50 with OAuth2AccessToken

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

the class ServletOAuth2AuthorizedClientExchangeFilterFunctionITests method requestWhenAuthorizedButExpiredThenRefreshAndSendRequest.

@Test
public void requestWhenAuthorizedButExpiredThenRefreshAndSendRequest() {
    // @formatter:off
    String accessTokenResponse = "{\n" + "   \"access_token\": \"refreshed-access-token\",\n" + "   \"token_type\": \"bearer\",\n" + "   \"expires_in\": \"3600\"\n" + "}\n";
    String clientResponse = "{\n" + "	\"attribute1\": \"value1\",\n" + "	\"attribute2\": \"value2\"\n" + "}\n";
    // @formatter:on
    this.server.enqueue(jsonResponse(accessTokenResponse));
    this.server.enqueue(jsonResponse(clientResponse));
    ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().tokenUri(this.serverUrl).build();
    given(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration.getRegistrationId()))).willReturn(clientRegistration);
    Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
    Instant expiresAt = issuedAt.plus(Duration.ofHours(1));
    OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "expired-access-token", issuedAt, expiresAt, new HashSet<>(Arrays.asList("read", "write")));
    OAuth2RefreshToken refreshToken = TestOAuth2RefreshTokens.refreshToken();
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, this.authentication.getName(), accessToken, refreshToken);
    doReturn(authorizedClient).when(this.authorizedClientRepository).loadAuthorizedClient(eq(clientRegistration.getRegistrationId()), eq(this.authentication), eq(this.request));
    this.webClient.get().uri(this.serverUrl).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId(clientRegistration.getRegistrationId())).retrieve().bodyToMono(String.class).block();
    assertThat(this.server.getRequestCount()).isEqualTo(2);
    ArgumentCaptor<OAuth2AuthorizedClient> authorizedClientCaptor = ArgumentCaptor.forClass(OAuth2AuthorizedClient.class);
    verify(this.authorizedClientRepository).saveAuthorizedClient(authorizedClientCaptor.capture(), eq(this.authentication), eq(this.request), eq(this.response));
    OAuth2AuthorizedClient refreshedAuthorizedClient = authorizedClientCaptor.getValue();
    assertThat(refreshedAuthorizedClient.getClientRegistration()).isSameAs(clientRegistration);
    assertThat(refreshedAuthorizedClient.getAccessToken().getTokenValue()).isEqualTo("refreshed-access-token");
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) Instant(java.time.Instant) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)265 Test (org.junit.Test)177 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)144 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)93 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)71 Test (org.junit.jupiter.api.Test)48 Date (java.util.Date)44 Authentication (org.springframework.security.core.Authentication)41 HashMap (java.util.HashMap)39 TokenRequest (org.springframework.security.oauth2.provider.TokenRequest)35 Instant (java.time.Instant)32 DefaultOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken)31 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)28 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)26 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)21 DefaultExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken)20 DBUnitTest (org.orcid.test.DBUnitTest)19 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)19 OAuth2RefreshToken (org.springframework.security.oauth2.core.OAuth2RefreshToken)19 Map (java.util.Map)18