Java Code Examples for org.springframework.security.oauth2.client.OAuth2AuthorizedClient#getAccessToken()

The following examples show how to use org.springframework.security.oauth2.client.OAuth2AuthorizedClient#getAccessToken() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
Source File: RefreshExpiredTokenFilter.java    From oauth2-client with MIT License 4 votes vote down vote up
@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);
}