org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse Java Examples
The following examples show how to use
org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse.
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: JwtBearerOAuth2AuthorizedClientProvider.java From oauth2-protocol-patterns with Apache License 2.0 | 8 votes |
/** * Attempt to authorize the {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided {@code context}. * Returns {@code null} if authorization is not supported, * e.g. the client's {@link ClientRegistration#getAuthorizationGrantType() authorization grant type} * is not {@link JwtBearerGrantRequest#JWT_BEARER_GRANT_TYPE jwt-bearer}. * * @param context the context that holds authorization-specific state for the client * @return the {@link OAuth2AuthorizedClient} or {@code null} if authorization is not supported */ @Override @Nullable public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) { Assert.notNull(context, "context cannot be null"); ClientRegistration clientRegistration = context.getClientRegistration(); if (!JwtBearerGrantRequest.JWT_BEARER_GRANT_TYPE.equals(clientRegistration.getAuthorizationGrantType())) { return null; } Jwt jwt = context.getAttribute(JWT_ATTRIBUTE_NAME); if (jwt == null) { return null; } OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient(); if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) { // If client is already authorized but access token is NOT expired than no need for re-authorization return null; } JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, jwt); OAuth2AccessTokenResponse tokenResponse = this.accessTokenResponseClient.getTokenResponse(jwtBearerGrantRequest); return new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(), tokenResponse.getAccessToken()); }
Example #2
Source File: UaaAuthorizationHeaderUtil.java From jhipster-registry with Apache License 2.0 | 6 votes |
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 #3
Source File: AuthorizationHeaderUtil.java From jhipster-registry with Apache License 2.0 | 6 votes |
private OAuth2AccessTokenResponse refreshTokenClient(OAuth2AuthorizedClient currentClient) { MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>(); formParameters.add(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.REFRESH_TOKEN.getValue()); formParameters.add(OAuth2ParameterNames.REFRESH_TOKEN, currentClient.getRefreshToken().getTokenValue()); formParameters.add(OAuth2ParameterNames.CLIENT_ID, currentClient.getClientRegistration().getClientId()); RequestEntity requestEntity = RequestEntity .post(URI.create(currentClient.getClientRegistration().getProviderDetails().getTokenUri())) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .body(formParameters); try { RestTemplate r = restTemplate(currentClient.getClientRegistration().getClientId(), currentClient.getClientRegistration().getClientSecret()); ResponseEntity<OAuthIdpTokenResponseDTO> responseEntity = r.exchange(requestEntity, OAuthIdpTokenResponseDTO.class); return toOAuth2AccessTokenResponse(responseEntity.getBody()); } catch (OAuth2AuthorizationException e) { log.error("Unable to refresh token", e); throw new OAuth2AuthenticationException(e.getError(), e); } }
Example #4
Source File: AuthorizationHeaderUtil.java From jhipster-registry with Apache License 2.0 | 6 votes |
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 #5
Source File: UaaAuthorizationHeaderUtilIT.java From jhipster-registry with Apache License 2.0 | 6 votes |
@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 #6
Source File: CustomAccessTokenResponseConverter.java From messaging-app with Apache License 2.0 | 5 votes |
@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 #7
Source File: DefaultJwtBearerTokenResponseClient.java From oauth2-protocol-patterns with Apache License 2.0 | 5 votes |
@Override public OAuth2AccessTokenResponse getTokenResponse(JwtBearerGrantRequest jwtBearerGrantRequest) { Assert.notNull(jwtBearerGrantRequest, "jwtBearerGrantRequest cannot be null"); RequestEntity<?> request = this.requestEntityConverter.convert(jwtBearerGrantRequest); ResponseEntity<OAuth2AccessTokenResponse> response; try { response = this.restOperations.exchange(request, OAuth2AccessTokenResponse.class); } catch (RestClientException ex) { OAuth2Error oauth2Error = new OAuth2Error(INVALID_TOKEN_RESPONSE_ERROR_CODE, "An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response: " + ex.getMessage(), null); throw new OAuth2AuthorizationException(oauth2Error, ex); } OAuth2AccessTokenResponse tokenResponse = response.getBody(); if (CollectionUtils.isEmpty(tokenResponse.getAccessToken().getScopes())) { // As per spec, in Section 5.1 Successful Access Token Response // https://tools.ietf.org/html/rfc6749#section-5.1 // If AccessTokenResponse.scope is empty, then default to the scope // originally requested by the client in the Token Request tokenResponse = OAuth2AccessTokenResponse.withResponse(tokenResponse) .scopes(jwtBearerGrantRequest.getClientRegistration().getScopes()) .build(); } return tokenResponse; }
Example #8
Source File: DemoApplicationTests.java From keycloak-springsecurity5-sample with GNU General Public License v3.0 | 5 votes |
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 #9
Source File: UaaAuthorizationHeaderUtilIT.java From jhipster-registry with Apache License 2.0 | 5 votes |
@Test public void testAuthorizationHeaderWithNotExistingAuthorizedClient() { doReturn(ResponseEntity.ok(createAccessTokenResponse("tokenValue"))) .when(restTemplate).exchange(any(RequestEntity.class), ArgumentMatchers.<Class<OAuth2AccessTokenResponse>>any()); String authorizationHeader = authorizationHeaderUtil.getAuthorizationHeader(); assertThat(authorizationHeader).isNotEmpty(); assertThat(authorizationHeader).isEqualTo("Bearer tokenValue"); }
Example #10
Source File: UaaAuthorizationHeaderUtilIT.java From jhipster-registry with Apache License 2.0 | 5 votes |
private OAuth2AccessTokenResponse createAccessTokenResponse(String tokenValue) { return OAuth2AccessTokenResponse .withToken(tokenValue) .tokenType(OAuth2AccessToken.TokenType.BEARER) .expiresIn(Instant.now().plusSeconds(3600).getEpochSecond()) .build(); }
Example #11
Source File: LinkedinTokenResponseConverter.java From tutorials with MIT License | 5 votes |
@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 #12
Source File: RefreshExpiredTokenFilter.java From oauth2-client with MIT License | 4 votes |
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { log.debug("entering Refresh ExpiredToken Filter......"); /** * check if authentication is done. */ Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (null != authentication && authentication instanceof OAuth2AuthenticationToken) { OAuth2AuthenticationToken oldOAuth2Token = (OAuth2AuthenticationToken) authentication; OAuth2AuthorizedClient authorizedClient = this.oAuth2AuthorizedClientService .loadAuthorizedClient(oldOAuth2Token.getAuthorizedClientRegistrationId(), oldOAuth2Token.getName()); /** * Check whether token is expired. */ if (authorizedClient != null && isExpired(authorizedClient.getAccessToken())) { try { log.info("===================== Token Expired , trying to refresh"); ClientRegistration clientRegistration = authorizedClient.getClientRegistration(); /* * Call Auth server token endpoint to refresh token. */ OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration, authorizedClient.getAccessToken(), authorizedClient.getRefreshToken()); OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenResponseClient.getTokenResponse(refreshTokenGrantRequest); OAuth2User newOAuth2User = oAuth2UserService.loadUser(new OAuth2UserRequest(clientRegistration, accessTokenResponse.getAccessToken())); /* * Create new authentication(OAuth2AuthenticationToken). */ OAuth2AuthenticationToken updatedUser = new OAuth2AuthenticationToken(newOAuth2User, newOAuth2User.getAuthorities(), oldOAuth2Token.getAuthorizedClientRegistrationId()); /* * Update access_token and refresh_token by saving new authorized client. */ OAuth2AuthorizedClient updatedAuthorizedClient = new OAuth2AuthorizedClient(clientRegistration, oldOAuth2Token.getName(), accessTokenResponse.getAccessToken(), accessTokenResponse.getRefreshToken()); this.oAuth2AuthorizedClientService.saveAuthorizedClient(updatedAuthorizedClient, updatedUser); /* * Set new authentication in SecurityContextHolder. */ SecurityContextHolder.getContext().setAuthentication(updatedUser); Cookie tokenCookie = new Cookie("access_token", accessTokenResponse.getAccessToken().getTokenValue()); tokenCookie.setHttpOnly(true); tokenCookie.setDomain(cookieDomain); tokenCookie.setPath("/"); response.addCookie(tokenCookie); log.info("===================== Refresh Token Done !"); } catch (OAuth2AuthorizationException e) { log.info("Refresh ExpiredToken exception", e); SecurityContextHolder.getContext().setAuthentication(null); } } } log.debug("exit Refresh ExpiredToken Filter......"); filterChain.doFilter(request, response); }
Example #13
Source File: DataFlowConfiguration.java From composed-task-runner with Apache License 2.0 | 4 votes |
/** * @param clientRegistrations Can be null. Only required for Client Credentials Grant authentication * @param clientCredentialsTokenResponseClient Can be null. Only required for Client Credentials Grant authentication * @return DataFlowOperations */ @Bean public DataFlowOperations dataFlowOperations( @Autowired(required = false) ClientRegistrationRepository clientRegistrations, @Autowired(required = false) OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> clientCredentialsTokenResponseClient) { final RestTemplate restTemplate = DataFlowTemplate.getDefaultDataflowRestTemplate(); validateUsernamePassword(this.properties.getDataflowServerUsername(), this.properties.getDataflowServerPassword()); HttpClientConfigurer clientHttpRequestFactoryBuilder = null; if (this.properties.getOauth2ClientCredentialsClientId() != null || StringUtils.hasText(this.properties.getDataflowServerAccessToken()) || (StringUtils.hasText(this.properties.getDataflowServerUsername()) && StringUtils.hasText(this.properties.getDataflowServerPassword()))) { clientHttpRequestFactoryBuilder = HttpClientConfigurer.create(this.properties.getDataflowServerUri()); } String accessTokenValue = null; if (this.properties.getOauth2ClientCredentialsClientId() != null) { final ClientRegistration clientRegistration = clientRegistrations.findByRegistrationId("default"); final OAuth2ClientCredentialsGrantRequest grantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration); final OAuth2AccessTokenResponse res = clientCredentialsTokenResponseClient.getTokenResponse(grantRequest); accessTokenValue = res.getAccessToken().getTokenValue(); logger.debug("Configured OAuth2 Client Credentials for accessing the Data Flow Server"); } else if (StringUtils.hasText(this.properties.getDataflowServerAccessToken())) { accessTokenValue = this.properties.getDataflowServerAccessToken(); logger.debug("Configured OAuth2 Access Token for accessing the Data Flow Server"); } else if (StringUtils.hasText(this.properties.getDataflowServerUsername()) && StringUtils.hasText(this.properties.getDataflowServerPassword())) { accessTokenValue = null; clientHttpRequestFactoryBuilder.basicAuthCredentials(properties.getDataflowServerUsername(), properties.getDataflowServerPassword()); logger.debug("Configured basic security for accessing the Data Flow Server"); } else { logger.debug("Not configuring basic security for accessing the Data Flow Server"); } if (accessTokenValue != null) { restTemplate.getInterceptors().add(new OAuth2AccessTokenProvidingClientHttpRequestInterceptor(accessTokenValue)); } if (clientHttpRequestFactoryBuilder != null) { restTemplate.setRequestFactory(clientHttpRequestFactoryBuilder.buildClientHttpRequestFactory()); } return new DataFlowTemplate(this.properties.getDataflowServerUri(), restTemplate); }
Example #14
Source File: DataFlowConfiguration.java From spring-cloud-dataflow with Apache License 2.0 | 4 votes |
/** * @param clientRegistrations Can be null. Only required for Client Credentials Grant authentication * @param clientCredentialsTokenResponseClient Can be null. Only required for Client Credentials Grant authentication * @return DataFlowOperations */ @Bean public DataFlowOperations dataFlowOperations( @Autowired(required = false) ClientRegistrationRepository clientRegistrations, @Autowired(required = false) OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> clientCredentialsTokenResponseClient) { final RestTemplate restTemplate = DataFlowTemplate.getDefaultDataflowRestTemplate(); validateUsernamePassword(this.properties.getDataflowServerUsername(), this.properties.getDataflowServerPassword()); HttpClientConfigurer clientHttpRequestFactoryBuilder = null; if (this.properties.getOauth2ClientCredentialsClientId() != null || StringUtils.hasText(this.properties.getDataflowServerAccessToken()) || (StringUtils.hasText(this.properties.getDataflowServerUsername()) && StringUtils.hasText(this.properties.getDataflowServerPassword()))) { clientHttpRequestFactoryBuilder = HttpClientConfigurer.create(this.properties.getDataflowServerUri()); } String accessTokenValue = null; if (this.properties.getOauth2ClientCredentialsClientId() != null) { final ClientRegistration clientRegistration = clientRegistrations.findByRegistrationId("default"); final OAuth2ClientCredentialsGrantRequest grantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration); final OAuth2AccessTokenResponse res = clientCredentialsTokenResponseClient.getTokenResponse(grantRequest); accessTokenValue = res.getAccessToken().getTokenValue(); logger.debug("Configured OAuth2 Client Credentials for accessing the Data Flow Server"); } else if (StringUtils.hasText(this.properties.getDataflowServerAccessToken())) { accessTokenValue = this.properties.getDataflowServerAccessToken(); logger.debug("Configured OAuth2 Access Token for accessing the Data Flow Server"); } else if (StringUtils.hasText(this.properties.getDataflowServerUsername()) && StringUtils.hasText(this.properties.getDataflowServerPassword())) { accessTokenValue = null; clientHttpRequestFactoryBuilder.basicAuthCredentials(properties.getDataflowServerUsername(), properties.getDataflowServerPassword()); logger.debug("Configured basic security for accessing the Data Flow Server"); } else { logger.debug("Not configuring basic security for accessing the Data Flow Server"); } if (accessTokenValue != null) { restTemplate.getInterceptors().add(new OAuth2AccessTokenProvidingClientHttpRequestInterceptor(accessTokenValue)); } if (clientHttpRequestFactoryBuilder != null) { restTemplate.setRequestFactory(clientHttpRequestFactoryBuilder.buildClientHttpRequestFactory()); } return new DataFlowTemplate(this.properties.getDataflowServerUri(), restTemplate); }
Example #15
Source File: CustomTokenResponseConverter.java From tutorials with MIT License | 4 votes |
@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(); }