How to access external URL which requires OAuth2 via Spring Boot?

spring boot rest oauth2 example
spring boot oauth2 client
spring boot oauth2 authorization code example
spring boot + oauth2 + mysql
spring boot oauth2 get access token
spring boot 2 oauth2 authorization server
spring boot security oauth2 example mkyong

Currently, the mechanism that we use for authenticating against a server which requires OAuth2 is to write a Java program which contains a main() method, which runs an HttpClient to generate an OAuth2 access token by using this call:

This returns the following JSON payload:

    "access_token": "eyJhbGciOi786I1NiJ9.eyJ1c2VybmFtZSI6bnVsbCwiZGV2aWNlSWQiOm51bGwsImNsaWVudElkIjoiaUxIdVhlVUxGQmRXNEIxZG1SWTBNaFJPTVJRbmxmZUsiLCJhZElkIjpudWxsLCJleHAiOjE1MjU0MjY4LMYsImlhdCI6MTUyNTQyMzE0Nn0.Zz_uhXqOF2ykC24mNBWHnQ_Vmx-jfQs3X4qcmmN0-Sk",
    "token_type": "Bearer",
    "expires_in": 3600,
    "refresh_token": null,
    "scope": null

After obtaining the access token, we are able to run queries using JSON against the authorized website / service.


  1. Inside a Spring Boot Microservice (2.0.1.RELEASE), how can one use Spring Security or just an HttpClient to use clientId, clientSecret and grant_type to automatically provide a global access token inside each REST call (which might be an HTTP Post) from the REST controller layer?

  2. Can someone show a code sample of how to use Spring Security or a different library to just send the clientId, clientSecret, and grant_type to obtain an OAuth2 access token?

  3. What to do (using the library from question # 2) if the OAuth2 token expires?

1) You dont need spring security .Just use 'io.jsonwebtoken.Jwts'. You can use any number of parameters to generate the JWT token . You can use a component inside your Spring boot application to generate the JWT token .

Then create a Token service that will use this bean and perform :generate access token , validate access token and refresh the token .

2) Sample : @Component public String createJwtToken(User user, TokenType type, ClientKey clientKey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {

   String userName = user.getUsername();

   Date currentTime = new Date();

   String token = Jwts.builder()
     .claim(Constants.NAME_KEY, Constants.NAME_VALUE)
     .claim(Constants.USER_TOKEN_KEY, clientKey.getKey())
     .claim(Constants.SCOPE_KEY, Constants.SCOPE_VALUE)
     .setHeaderParam(Constants.TOKEN_TYP, Constants.TOKEN_JWT)
     .signWith(SignatureAlgorithm.HS256, key)
   return encrypt(token);


3) Whenever you generate the token for the first time you generate 2 tokens : accessToken and Refresh Token . AccessToken is short lived and expires soon . - say 5 mins . The refresh token has a onger expiry duration : eg: 20 mins .

Purpose of refresh token is that you can use the refresh token to generate the new access token . So when ur access token expires, just make a call to the refresh token method by passing ur refresh token . This method should return the user from redis with the new access token .


R Rai

How to access external URL which requires OAuth2 via Spring Boot?, Currently, the mechanism that we use for authenticating against a server which requires OAuth2 is to write a Java program which contains a  simple: a very basic static app with just a home page and unconditional login via Spring Boot’s OAuth 2.0 configuration properties (if you visit the home page, you will be automatically redirected to GitHub). click: adds an explicit link that the user has to click to login. logout: adds a logout link as well for authenticated users.

Found an OAuth2Client which open sourced and offered by IBM:

Tutorial, All samples are implemented using the native OAuth 2.0 support in Spring Boot. Authorization callback URL as http://localhost:8080/login/oauth2/code/github and click It then uses the access token to ask GitHub for some personal details (only needs and can be populated, fully or partially, from external authentication. Refresh token is issued (along with access token) to the client by the authorization server and is used to obtain a new access token when the current access token becomes invalid or expires, or to obtain additional access tokens with identical or narrower scope (access tokens may have a shorter lifetime and fewer permissions than authorized by the resource owner). Issuing a refresh token is optional at the discretion of the authorization server.

Also, just used RestTemplate:

String accessToken = OAuth2Client.generateAccessToken();
RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer "+accessToken);

HttpEntity<String> entity = new HttpEntity<String>(request,headers);
String response = restTemplate.postForObject(url, entity, String.class);

Very easy!

Using Spring Security 5 to integrate with OAuth 2-secured services , When you try to access a page without having been previously authenticated, After a successful authentication with an external OAuth 2 service, the desirable behavior for most APIs which require all requests to be authorized. details (such as the authorization URL) in your application configuration. In this post, we look at how to secure REST services using OAuth2 and Spring Boot through a helpful bank-credit card example to demonstrate an OAuth protocol. Securing REST Services With OAuth2 in

Spring Boot 2, Client – the application (user is using) which require access to user data on the To create authorization server using spring security oauth2 module, we need to diagram, first step is to get authorizarion grant from resource owner from URL  We’ll start with integrating Okta’s OAuth service using Spring Boot 1.5.19 and Spring Security 4.2.x and then replicate the same motion using Spring Boot 2.1.3 and Spring Security 5.1. To make

Spring Boot OAuth2 Part 2, In this tutorial we implement OAuth2 using Spring Boot. For getting the access token from the resource server the changes are only required at the client to allow the request to the url /user/getEmployeesList with valid access token and  Spring Boot + Spring Security + OAuth2. In this tutorial we explain how to secure a Spring Boot application using OAuth2. If you follow the steps in order, you’ll get a fully working secured application which authenticates user requests through Google API.

Using Spring Boot for OAuth2 and JWT REST Protection, Access token is then sent from client to server (acting as resource server) on each request for protected resource access; Server responds with required protected  The application is built on top of Spring Boot. More on setting up a Spring Boot application can be found in the Spring Boot application on Tomcat article. Enable OAuth2 Through Spring Boot

  • Thanks Rai - Your code sample gave me a lot of issues in Eclipse. I don't have a user and I don't know where the package import is for Constants comes from. I just need to find a Java library which can take a client_id, client_secret, and grant_type = client_credentials. I don't l know what to put for TokenType, ClientKey, and tokenIssuer?
  • You are generating the token on behalf of some entity . It could be a User, it could be an Organization or it could be a System Identifier . I just gave you an example of a user .
  • Constants, just create a class to store static values: public class Constants {public static final String TOKEN_TYP = "typ"; public static final String TOKEN_JWT = "JWT"; public static final String TOKEN_TYPE = "TOKEN_TYPE"; public static final String USER_TOKEN_KEY = "USER_KEY"; public static final TimeUnit TOKEN_TIMEUNIT = TimeUnit.MINUTES; public static final String NAME_KEY = "name"; public static final String NAME_VALUE = "COMPAN"; } TokenType, ClientKey, and tokenIssuer are just parameters used to generate ur token . You can replace these with any paraeters you need .