org.springframework.security.oauth2.core.OAuth2AccessToken Java Examples

The following examples show how to use org.springframework.security.oauth2.core.OAuth2AccessToken. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GitLabOAuth2ProviderTest.java    From gaia with Mozilla Public License 2.0 7 votes vote down vote up
@Test
void getOAuth2User_shouldReturnANewOAuthUser() {
    // given
    var attributes = new HashMap<String, Object>();
    var user = mock(DefaultOAuth2User.class);
    var client = mock(OAuth2AuthorizedClient.class);
    var registration = ClientRegistration
            .withRegistrationId("test_registration_id")
            .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
            .clientId("test_client_id")
            .redirectUriTemplate("test_uri_template")
            .authorizationUri("test_authorization_uri")
            .tokenUri("test_token_uri")
            .build();
    var accessToken = mock(OAuth2AccessToken.class);

    // when
    when(user.getAttributes()).thenReturn(attributes);
    when(client.getClientRegistration()).thenReturn(registration);
    when(client.getAccessToken()).thenReturn(accessToken);
    when(accessToken.getTokenValue()).thenReturn("test_token");
    var result = gitLabOAuth2Provider.getOAuth2User(user, client);

    // then
    assertThat(result).isNotNull()
            .hasFieldOrPropertyWithValue("provider", "test_registration_id")
            .hasFieldOrPropertyWithValue("token", "test_token")
            .hasFieldOrPropertyWithValue("attributes", attributes);
}
 
Example #2
Source File: AuthorizationHeaderUtil.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
private OAuth2AccessTokenResponse toOAuth2AccessTokenResponse(OAuthIdpTokenResponseDTO oAuthIdpResponse) {
    Map<String, Object> additionalParameters = new HashMap<>();
    additionalParameters.put("id_token", oAuthIdpResponse.getIdToken());
    additionalParameters.put("not-before-policy", oAuthIdpResponse.getNotBefore());
    additionalParameters.put("refresh_expires_in", oAuthIdpResponse.getRefreshExpiresIn());
    additionalParameters.put("session_state", oAuthIdpResponse.getSessionState());
    return OAuth2AccessTokenResponse.withToken(oAuthIdpResponse.getAccessToken())
        .expiresIn(oAuthIdpResponse.getExpiresIn())
        .refreshToken(oAuthIdpResponse.getRefreshToken())
        .scopes(Pattern.compile("\\s").splitAsStream(oAuthIdpResponse.getScope()).collect(Collectors.toSet()))
        .tokenType(OAuth2AccessToken.TokenType.BEARER)
        .additionalParameters(additionalParameters)
        .build();
}
 
Example #3
Source File: UaaAuthorizationHeaderUtilIT.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthorizationHeaderWithExpiredAccessToken() {
    OAuth2AccessToken accessToken = new OAuth2AccessToken(
        OAuth2AccessToken.TokenType.BEARER,
        "existingTokenValue",
        Instant.now().minus(Duration.ofHours(1)),
        Instant.now().minus(Duration.ofMinutes(2)));
    authorizedClientService.saveAuthorizedClient(createAuthorizedClient(accessToken), authentication);

    doReturn(ResponseEntity.ok(createAccessTokenResponse("refreshTokenValue")))
        .when(restTemplate).exchange(any(RequestEntity.class), ArgumentMatchers.<Class<OAuth2AccessTokenResponse>>any());

    String authorizationHeader = authorizationHeaderUtil.getAuthorizationHeader();

    assertThat(authorizationHeader).isNotEmpty();
    assertThat(authorizationHeader).isEqualTo("Bearer refreshTokenValue");
}
 
Example #4
Source File: UaaAuthorizationHeaderUtil.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
private OAuth2AccessToken retrieveNewAccessToken(ClientRegistration clientRegistration) {
    MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>();
    formParameters.add(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.CLIENT_CREDENTIALS.getValue());
    RequestEntity requestEntity = RequestEntity
        .post(URI.create(clientRegistration.getProviderDetails().getTokenUri()))
        .contentType(MediaType.APPLICATION_FORM_URLENCODED)
        .body(formParameters);

    try {
        ResponseEntity<OAuth2AccessTokenResponse> responseEntity = this.uaaRestTemplate.exchange(requestEntity, OAuth2AccessTokenResponse.class);
        return Objects.requireNonNull(responseEntity.getBody()).getAccessToken();
    } catch (OAuth2AuthorizationException e) {
        log.error("Unable to get access token", e);
        throw new OAuth2AuthenticationException(e.getError(), e);
    }
}
 
Example #5
Source File: UaaAuthorizationHeaderUtil.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
private Optional<OAuth2AuthorizedClient> refreshAuthorizedClient(Authentication authentication) {
    ClientRegistration clientRegistration = clientRegistrationRepository.findByRegistrationId(CLIENT_REGISTRATION_ID);
    if (clientRegistration == null) {
        throw new IllegalArgumentException("Invalid Client Registration with Id: " + CLIENT_REGISTRATION_ID);
    }

    OAuth2AccessToken accessToken = retrieveNewAccessToken(clientRegistration);
    if (accessToken == null) {
        log.info("Unable to get access token for user");
        return Optional.empty();
    }
    OAuth2AuthorizedClient updatedAuthorizedClient = new OAuth2AuthorizedClient(
        clientRegistration,
        authentication.getName(),
        accessToken
    );
    clientRegistrationService.saveAuthorizedClient(updatedAuthorizedClient, authentication);
    return Optional.of(updatedAuthorizedClient);
}
 
Example #6
Source File: CFUAAOAuth2ClientController.java    From tutorials with MIT License 6 votes vote down vote up
@RequestMapping("/")
public String index(OAuth2AuthenticationToken authenticationToken) {
    OAuth2AuthorizedClient oAuth2AuthorizedClient = this.authorizedClientService.loadAuthorizedClient(authenticationToken.getAuthorizedClientRegistrationId(), authenticationToken.getName());
    OAuth2AccessToken oAuth2AccessToken = oAuth2AuthorizedClient.getAccessToken();

    String response = "Hello, " + authenticationToken.getPrincipal().getName();
    response += "</br></br>";
    response += "Here is your accees token :</br>" + oAuth2AccessToken.getTokenValue();
    response += "</br>";
    response += "</br>You can use it to call these Resource Server APIs:";
    response += "</br></br>";
    response += "<a href='/read'>Call Resource Server Read API</a>";
    response += "</br>";
    response += "<a href='/write'>Call Resource Server Write API</a>";
    return response;
}
 
Example #7
Source File: CFUAAOAuth2ClientController.java    From tutorials with MIT License 6 votes vote down vote up
private String callResourceServer(OAuth2AuthenticationToken authenticationToken, String url) {
    OAuth2AuthorizedClient oAuth2AuthorizedClient = this.authorizedClientService.loadAuthorizedClient(authenticationToken.getAuthorizedClientRegistrationId(), authenticationToken.getName());
    OAuth2AccessToken oAuth2AccessToken = oAuth2AuthorizedClient.getAccessToken();

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer " + oAuth2AccessToken.getTokenValue());

    HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
    ResponseEntity<String> responseEntity = null;

    String response = null;
    try {
        responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        response = responseEntity.getBody();
    } catch (HttpClientErrorException e) {
        response = e.getMessage();
    }
    return response;
}
 
Example #8
Source File: AuthorizationHeaderFilter.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
private Optional<String> getAuthorizationHeader() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
    OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(
            oauthToken.getAuthorizedClientRegistrationId(),
            oauthToken.getName());

    OAuth2AccessToken accessToken = client.getAccessToken();

    if (accessToken == null) {
        return Optional.empty();
    } else {
        String tokenType = accessToken.getTokenType().getValue();
        String authorizationHeaderValue = String.format("%s %s", tokenType, accessToken.getTokenValue());
        return Optional.of(authorizationHeaderValue);
    }
}
 
Example #9
Source File: AuthorizationHeaderUtil.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
public Optional<String> getAuthorizationHeader() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
    OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(
        oauthToken.getAuthorizedClientRegistrationId(),
        oauthToken.getName());

    OAuth2AccessToken accessToken = client.getAccessToken();

    if (accessToken == null) {
        return Optional.empty();
    } else {
        String tokenType = accessToken.getTokenType().getValue();
        String authorizationHeaderValue = String.format("%s %s", tokenType, accessToken.getTokenValue());
        return Optional.of(authorizationHeaderValue);
    }
}
 
Example #10
Source File: AuthorizationHeaderUtil.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
public Optional<String> getAuthorizationHeader() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
    OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(
        oauthToken.getAuthorizedClientRegistrationId(),
        oauthToken.getName());

    OAuth2AccessToken accessToken = client.getAccessToken();

    if (accessToken == null) {
        return Optional.empty();
    } else {
        String tokenType = accessToken.getTokenType().getValue();
        String authorizationHeaderValue = String.format("%s %s", tokenType, accessToken.getTokenValue());
        return Optional.of(authorizationHeaderValue);
    }
}
 
Example #11
Source File: AuthorizationHeaderUtil.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
public Optional<String> getAuthorizationHeader() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
    OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(
        oauthToken.getAuthorizedClientRegistrationId(),
        oauthToken.getName());

    OAuth2AccessToken accessToken = client.getAccessToken();

    if (accessToken == null) {
        return Optional.empty();
    } else {
        String tokenType = accessToken.getTokenType().getValue();
        String authorizationHeaderValue = String.format("%s %s", tokenType, accessToken.getTokenValue());
        return Optional.of(authorizationHeaderValue);
    }
}
 
Example #12
Source File: GitHubOAuth2ProviderTest.java    From gaia with Mozilla Public License 2.0 5 votes vote down vote up
@Test
void getOAuth2User_shouldReturnANewOAuthUser() {
    // given
    var attributes = new HashMap<String, Object>();
    var user = mock(DefaultOAuth2User.class);
    var client = mock(OAuth2AuthorizedClient.class);
    var registration = ClientRegistration
            .withRegistrationId("test_registration_id")
            .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
            .clientId("test_client_id")
            .redirectUriTemplate("test_uri_template")
            .authorizationUri("test_authorization_uri")
            .tokenUri("test_token_uri")
            .build();
    var accessToken = mock(OAuth2AccessToken.class);

    // when
    when(user.getAttributes()).thenReturn(attributes);
    when(client.getClientRegistration()).thenReturn(registration);
    when(client.getAccessToken()).thenReturn(accessToken);
    when(accessToken.getTokenValue()).thenReturn("test_token");
    var result = gitHubOAuth2Provider.getOAuth2User(user, client);

    // then
    assertThat(result).isNotNull()
            .hasFieldOrPropertyWithValue("provider", "test_registration_id")
            .hasFieldOrPropertyWithValue("token", "test_token")
            .hasFieldOrPropertyWithValue("attributes", attributes);
}
 
Example #13
Source File: TokenRelayGatewayFilterFactoryTests.java    From spring-cloud-security with Apache License 2.0 5 votes vote down vote up
@Test
public void whenPrincipalExistsAuthorizationHeaderAdded() {
	OAuth2AccessToken accessToken = mock(OAuth2AccessToken.class);
	when(accessToken.getTokenValue()).thenReturn("mytoken");

	ClientRegistration clientRegistration = ClientRegistration
			.withRegistrationId("myregistrationid")
			.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
			.clientId("myclientid").tokenUri("mytokenuri").build();
	OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(
			clientRegistration, "joe", accessToken);

	when(repository.loadAuthorizedClient(anyString(),
			any(OAuth2AuthenticationToken.class), any(ServerWebExchange.class)))
					.thenReturn(Mono.just(authorizedClient));

	OAuth2AuthenticationToken authenticationToken = new OAuth2AuthenticationToken(
			mock(OAuth2User.class), Collections.emptyList(), "myId");
	SecurityContextImpl securityContext = new SecurityContextImpl(
			authenticationToken);
	SecurityContextServerWebExchange exchange = new SecurityContextServerWebExchange(
			mockExchange, Mono.just(securityContext));

	filter.filter(exchange, filterChain).block(TIMEOUT);

	assertThat(request.getHeaders()).containsEntry(HttpHeaders.AUTHORIZATION,
			Collections.singletonList("Bearer mytoken"));
}
 
Example #14
Source File: TokenRelayGatewayFilterFactory.java    From spring-cloud-security with Apache License 2.0 5 votes vote down vote up
private ServerWebExchange withBearerAuth(ServerWebExchange exchange,
		OAuth2AccessToken accessToken) {
	return exchange.mutate()
			.request(r -> r.headers(
					headers -> headers.setBearerAuth(accessToken.getTokenValue())))
			.build();
}
 
Example #15
Source File: UaaAuthorizationHeaderUtilIT.java    From jhipster-registry with Apache License 2.0 5 votes vote down vote up
private OAuth2AccessTokenResponse createAccessTokenResponse(String tokenValue) {
    return OAuth2AccessTokenResponse
        .withToken(tokenValue)
        .tokenType(OAuth2AccessToken.TokenType.BEARER)
        .expiresIn(Instant.now().plusSeconds(3600).getEpochSecond())
        .build();
}
 
Example #16
Source File: UaaAuthorizationHeaderUtilIT.java    From jhipster-registry with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthorizationHeaderWithExistingAuthorizedClient() {
    // GIVEN
    OAuth2AccessToken accessToken = new OAuth2AccessToken(
        OAuth2AccessToken.TokenType.BEARER,
        "existingTokenValue",
        Instant.now().minus(Duration.ofHours(1)),
        Instant.now().plus(Duration.ofHours(1)));
    authorizedClientService.saveAuthorizedClient(createAuthorizedClient(accessToken), authentication);

    String authorizationHeader = authorizationHeaderUtil.getAuthorizationHeader();

    assertThat(authorizationHeader).isNotEmpty();
    assertThat(authorizationHeader).isEqualTo("Bearer existingTokenValue");
}
 
Example #17
Source File: LinkedinTokenResponseConverter.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessTokenResponse convert(Map<String, String> tokenResponseParameters) {
    String accessToken = tokenResponseParameters.get(OAuth2ParameterNames.ACCESS_TOKEN);
    long expiresIn = Long.valueOf(tokenResponseParameters.get(OAuth2ParameterNames.EXPIRES_IN));
    
    OAuth2AccessToken.TokenType accessTokenType = OAuth2AccessToken.TokenType.BEARER;

    return OAuth2AccessTokenResponse.withToken(accessToken)
        .tokenType(accessTokenType)
        .expiresIn(expiresIn)
        .build();
}
 
Example #18
Source File: AuthorizationHeaderUtil.java    From jhipster-registry with Apache License 2.0 5 votes vote down vote up
public Optional<String> getAuthorizationHeader() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
    String name = oauthToken.getName();
    String registrationId = oauthToken.getAuthorizedClientRegistrationId();
    OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(registrationId, name);

    if (null == client) {
        throw new OAuth2AuthorizationException(new OAuth2Error("access_denied", "The token is expired", null));
    }
    OAuth2AccessToken accessToken = client.getAccessToken();

    if (accessToken != null) {
        String tokenType = accessToken.getTokenType().getValue();
        String accessTokenValue = accessToken.getTokenValue();
        if (isExpired(accessToken)) {
            log.info("AccessToken expired, refreshing automatically");
            accessTokenValue = refreshToken(client, oauthToken);
            if (null == accessTokenValue) {
                SecurityContextHolder.getContext().setAuthentication(null);
                throw new OAuth2AuthorizationException(new OAuth2Error(OAuth2ErrorCodes.ACCESS_DENIED, "The token is expired", null));
            }
        }
        String authorizationHeaderValue = String.format("%s %s", tokenType, accessTokenValue);
        return Optional.of(authorizationHeaderValue);
    }
    return Optional.empty();
}
 
Example #19
Source File: DemoApplicationTests.java    From keycloak-springsecurity5-sample with GNU General Public License v3.0 5 votes vote down vote up
private OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> mockAccessTokenResponseClient() {
	OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234")
		.tokenType(OAuth2AccessToken.TokenType.BEARER)
		.expiresIn(60 * 1000)
		.build();

	OAuth2AccessTokenResponseClient tokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
	when(tokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse);
	return tokenResponseClient;
}
 
Example #20
Source File: CustomAccessTokenResponseConverter.java    From messaging-app with Apache License 2.0 5 votes vote down vote up
@Override
public OAuth2AccessTokenResponse convert(Map<String, String> tokenResponseParameters) {
	String accessToken = tokenResponseParameters.get(OAuth2ParameterNames.ACCESS_TOKEN);

	OAuth2AccessToken.TokenType accessTokenType = OAuth2AccessToken.TokenType.BEARER;

	long expiresIn = 0;
	if (tokenResponseParameters.containsKey(OAuth2ParameterNames.EXPIRES_IN)) {
		try {
			expiresIn = Long.valueOf(tokenResponseParameters.get(OAuth2ParameterNames.EXPIRES_IN));
		} catch (NumberFormatException ex) { }
	}

	Set<String> scopes = Collections.emptySet();
	if (tokenResponseParameters.containsKey(OAuth2ParameterNames.SCOPE)) {
		String scope = tokenResponseParameters.get(OAuth2ParameterNames.SCOPE);
		scopes = Arrays.stream(StringUtils.delimitedListToStringArray(scope, " ")).collect(Collectors.toSet());
	}

	Map<String, Object> additionalParameters = new LinkedHashMap<>();
	tokenResponseParameters.entrySet().stream()
			.filter(e -> !TOKEN_RESPONSE_PARAMETER_NAMES.contains(e.getKey()))
			.forEach(e -> additionalParameters.put(e.getKey(), e.getValue()));

	return OAuth2AccessTokenResponse.withToken(accessToken)
			.tokenType(accessTokenType)
			.expiresIn(expiresIn)
			.scopes(scopes)
			.additionalParameters(additionalParameters)
			.build();
}
 
Example #21
Source File: UserFeignClientInterceptor.java    From java-microservices-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(RequestTemplate template) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
    OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(
            oauthToken.getAuthorizedClientRegistrationId(),
            oauthToken.getName());

    OAuth2AccessToken accessToken = client.getAccessToken();
    template.header(AUTHORIZATION_HEADER, String.format("%s %s", BEARER_TOKEN_TYPE, accessToken.getTokenValue()));
}
 
Example #22
Source File: AuthorizationHeaderUtil.java    From jhipster-registry with Apache License 2.0 4 votes vote down vote up
private boolean isExpired(OAuth2AccessToken accessToken) {
    Instant now = Instant.now();
    Instant expiresAt = Objects.requireNonNull(accessToken.getExpiresAt());
    return now.isAfter(expiresAt.minus(Duration.ofMinutes(1L)));
}
 
Example #23
Source File: UaaAuthorizationHeaderUtil.java    From jhipster-registry with Apache License 2.0 4 votes vote down vote up
private boolean isExpired(OAuth2AccessToken accessToken) {
    Instant now = Instant.now();
    Instant expiresAt = Objects.requireNonNull(accessToken.getExpiresAt());
    return now.isAfter(expiresAt.minus(Duration.ofMinutes(1L)));
}
 
Example #24
Source File: UaaAuthorizationHeaderUtilIT.java    From jhipster-registry with Apache License 2.0 4 votes vote down vote up
private OAuth2AuthorizedClient createAuthorizedClient(OAuth2AccessToken accessToken) {
    ClientRegistration clientRegistration = clientRegistrationRepository.findByRegistrationId(CLIENT_REGISTRATION_ID);
    return new OAuth2AuthorizedClient(clientRegistration, authentication.getName(), accessToken);
}
 
Example #25
Source File: UaaAuthorizationHeaderUtil.java    From jhipster-registry with Apache License 2.0 4 votes vote down vote up
private String toAuthorizationHeaderValue(OAuth2AccessToken accessToken) {
    return String.format("%s %s", accessToken.getTokenType().getValue(), accessToken.getTokenValue());
}
 
Example #26
Source File: RefreshExpiredTokenFilter.java    From oauth2-client with MIT License 4 votes vote down vote up
private Boolean isExpired(OAuth2AccessToken oAuth2AccessToken) {
    Instant now = this.clock.instant();
    Instant expiresAt = oAuth2AccessToken.getExpiresAt();
    return now.isAfter(expiresAt.minus(this.accessTokenExpiresSkew));
}
 
Example #27
Source File: SecurityConfig.java    From oauth2-client with MIT License 4 votes vote down vote up
/**
 * 从access_token中直接抽取角色等信息
 * https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#oauth2login-advanced-map-authorities-oauth2userservice
 *
 * @return
 */
@SuppressWarnings("unchecked")
@Bean
public OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService() {

    return (userRequest) -> {
        String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName();
        if (!StringUtils.hasText(userNameAttributeName)) {
            userNameAttributeName = "sub";
        }
        OAuth2AccessToken accessToken = userRequest.getAccessToken();
        Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        try {
            SignedJWT jwt = SignedJWT.parse(accessToken.getTokenValue());
            String claimJsonString = jwt.getJWTClaimsSet().toJSONObject().toJSONString();
            Object document = com.jayway.jsonpath.Configuration.defaultConfiguration().jsonProvider().parse(claimJsonString);

            List<Object> authorities = JsonPath.using(conf).parse(document).read("$..roles");

            if (authorities == null || authorities.size() == 0) {
                authorities = JsonPath.using(conf).parse(document).read("$..authorities");
            }
            Collection<String> roles = new ArrayList<>();
            authorities.forEach(authorityItem -> {
                if (authorityItem instanceof String) {
                    roles.add((String) authorityItem);
                } else if (authorityItem instanceof JSONArray) {
                    roles.addAll((Collection<String>) authorityItem);
                } else if (authorityItem instanceof Collection) {
                    roles.addAll((Collection<String>) authorityItem);
                }
            });

            for (String authority : roles) {
                grantedAuthorities.add(new SimpleGrantedAuthority(authority));
            }
            Map<String, Object> userAttributes = new HashMap<>(16);
            userAttributes.put(userNameAttributeName, JsonPath.using(conf).parse(document).read("$." + userNameAttributeName));
            userAttributes.put("preferred_username", JsonPath.using(conf).parse(document).read("$.preferred_username"));
            userAttributes.put("email", JsonPath.using(conf).parse(document).read("$.email"));
            OAuth2User oAuth2User = new DefaultOAuth2User(grantedAuthorities, userAttributes, userNameAttributeName);

            return oAuth2User;
        } catch (Exception e) {
            log.error("oauth2UserService Exception", e);
        }
        return null;
    };
}
 
Example #28
Source File: CustomTokenResponseConverter.java    From tutorials with MIT License 4 votes vote down vote up
@Override
public OAuth2AccessTokenResponse convert(Map<String, String> tokenResponseParameters) {
    String accessToken = tokenResponseParameters.get(OAuth2ParameterNames.ACCESS_TOKEN);

    OAuth2AccessToken.TokenType accessTokenType = null;
    if (OAuth2AccessToken.TokenType.BEARER.getValue()
        .equalsIgnoreCase(tokenResponseParameters.get(OAuth2ParameterNames.TOKEN_TYPE))) {
        accessTokenType = OAuth2AccessToken.TokenType.BEARER;
    }

    long expiresIn = 0;
    if (tokenResponseParameters.containsKey(OAuth2ParameterNames.EXPIRES_IN)) {
        try {
            expiresIn = Long.valueOf(tokenResponseParameters.get(OAuth2ParameterNames.EXPIRES_IN));
        } catch (NumberFormatException ex) {
        }
    }

    Set<String> scopes = Collections.emptySet();
    if (tokenResponseParameters.containsKey(OAuth2ParameterNames.SCOPE)) {
        String scope = tokenResponseParameters.get(OAuth2ParameterNames.SCOPE);
        scopes = Arrays.stream(StringUtils.delimitedListToStringArray(scope, " "))
            .collect(Collectors.toSet());
    }

    String refreshToken = tokenResponseParameters.get(OAuth2ParameterNames.REFRESH_TOKEN);

    Map<String, Object> additionalParameters = new LinkedHashMap<>();
    tokenResponseParameters.entrySet()
        .stream()
        .filter(e -> !TOKEN_RESPONSE_PARAMETER_NAMES.contains(e.getKey()))
        .forEach(e -> additionalParameters.put(e.getKey(), e.getValue()));

    return OAuth2AccessTokenResponse.withToken(accessToken)
        .tokenType(accessTokenType)
        .expiresIn(expiresIn)
        .scopes(scopes)
        .refreshToken(refreshToken)
        .additionalParameters(additionalParameters)
        .build();
}