org.springframework.security.oauth2.core.OAuth2AuthorizationException Java Examples
The following examples show how to use
org.springframework.security.oauth2.core.OAuth2AuthorizationException.
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: UaaAuthorizationHeaderUtil.java From jhipster-registry with Apache License 2.0 | 6 votes |
public String getAuthorizationHeader() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Optional<OAuth2AuthorizedClient> client = Optional.ofNullable( clientRegistrationService.loadAuthorizedClient(CLIENT_REGISTRATION_ID, authentication.getName())); if (!client.isPresent() || client.get().getAccessToken() == null) { log.info("AccessToken not found, refreshing automatically"); client = refreshAuthorizedClient(authentication); } else if (isExpired(client.get().getAccessToken())) { log.info("AccessToken expired, refreshing automatically"); client = refreshAuthorizedClient(authentication); } return client.map(OAuth2AuthorizedClient::getAccessToken) .map(this::toAuthorizationHeaderValue) .orElseThrow(() -> new OAuth2AuthorizationException(new OAuth2Error(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT, "Unable to get access token for user", null))); }
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: SyncopeSRAWebExceptionHandler.java From syncope with Apache License 2.0 | 6 votes |
@Override public Mono<Void> handle(final ServerWebExchange exchange, final Throwable throwable) { if (throwable instanceof ConnectException || throwable instanceof NativeIoException || throwable instanceof NotFoundException) { LOG.error("ConnectException thrown", throwable); return doHandle(exchange, throwable, HttpStatus.NOT_FOUND); } else if (throwable instanceof OAuth2AuthorizationException) { LOG.error("OAuth2AuthorizationException thrown", throwable); return doHandle(exchange, throwable, HttpStatus.INTERNAL_SERVER_ERROR); } return Mono.error(throwable); }
Example #5
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 #6
Source File: AuthorizationHeaderUtil.java From jhipster-registry with Apache License 2.0 | 5 votes |
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 #7
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); }