How to use refresh token by using Keycloak Admin REST API - java

I'm trying to use Keycloak Admin REST API SDK.
Then, I want to use refresh token to generate access token.
I know that the following code code can generate access token by refresh token.
val token = Keycloak.getInstance(serverUrl,
realmName,
userName,
password,
clientId,
clientSecret)
.tokenManager()
.refreshToken()
But this code can only work on TokenManager.
I want to use any refresh token like following code by admin user.
// I hope to call token endpoint -> /realms/{realm}/protocol/openid-connect/token?grant_type=refresh_token...
val accessToken = tokenManager.refresh(String refreshToken);
Could any SDK Class refresh token as I want?

Related

How to refresh Google OAuth 2 Access Token Kotlin

I am trying to build an application that interacts with Google's API to pull data from the YouTube Data API. I have been able to get an access token and a refresh token by having the user authenticate manually but I want the program to run without user input. My current approach is to get a new access token each time the application run but this seems to, after some time, revoke the current refresh token for the user which I used to get a new access token. My code is below. Does anyone have any suggestions for what I am doing wrong or a better way to do this? Thanks
val scopes: ArrayList<String> = ArrayList()
scopes.add("https://www.googleapis.com/auth/youtube.readonly")
val tokenResponse: TokenResponse = GoogleRefreshTokenRequest(NetHttpTransport(), GsonFactory(), refreshToken, clientID, clientSecret)
.setScopes(scopes).setGrantType("refresh_token").execute()
tokenResponse.accessToken
val cred: GoogleCredential = GoogleCredential.Builder().setTransport(NetHttpTransport()).setJsonFactory(GsonFactory()).setClientSecrets(clientID, clientSecret).build().setAccessToken(tokenResponse.accessToken).setRefreshToken(tokenResponse.refreshToken)

How to generate JWT Token using Facebook credentials in Spring boot

I have one requirement that have to develop Spring boot Rest API for login using Facebook credentials and have to generate JWT token for this credentials and validate every request.
Thanks.
When the user logs in using facebook credentials, the user will be authenticated by the facebook and will issue the token that can be used for authorisation. My point is that once you authenticate the user on facebook, you get the credential. Instead of wrapping it into the JWT, store it somewhere with id and wrap that ID in the JWT. On each request, you will receive the JWT token and while authorising, you can get id from the JWT and get it from the persistence or store and authorise the user.
Let say you have the facebook tokens after login, then you have to store it somewhere using some id
String fbTokenId = storeFBToken(fbToken);. Using this token you can generate JWT token like:
Algorithm algorithm = Algorithm.HMAC256(key);
String token = JWT.create().withIssuer(author)
.withClaim("fbTokenId", fbTokenId)
.withSubject("user")
.sign(algorithm);
When you authorise the request, you will have the JWT token. Now you have to get verify the token and read the fbTokenId to verify it:
Algorithm algorithm = Algorithm.HMAC256(key);
JWTVerifier verifier = JWT.require(algorithm).withIssuer(author)
.build();
DecodedJWT jwt = verifier.verify(token);
String fbTokenId = jwt.getClaim("fbTokenId").as(String.class);
String fbToken = getFBTokenFromStore(fbTokenId);
Before you jump into this, make sure you understand stateless authentication and authorisation concepts especially with tokens.
Find a sample authentication application here

AccessTokens returned for Active Directory are different between sample projects

I've been experimenting with Azure Active Directory access for Java using two sample projects:
1) https://github.com/AzureAD/azure-activedirectory-library-for-java which builds a stand-alone war using OAuth tokens for security, and
2) https://github.com/Microsoft/azure-spring-boot/tree/master/azure-spring-boot-samples/azure-active-directory-spring-boot-backend-sample for spring-boot embeded containers
I've come across quite a difference in the way the APIs can be used, that I can't understand.
In both cases, I get an OAuth token for AD by logging in with my Azure credentials.
In the Http response, I get an authorizationCode of the form:
AQABAAIAAAD.....
Then using the following URL as an authContext:
https://login.microsoftonline.com/{tenantId}
I get a AuthenticationResult by making the following call:
Future<AuthenticationResult> future = authContext.acquireTokenByAuthorizationCode(authorizationCode, redirectUri, credential, null);
in the Adal4j project (1), the AuthenticationResult's AccessToken is of the form:
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6I...
Which I can use as a Bearer token in an HTTP call to retrieve the user's profile picture via https://graph.windows.net/myorganization/me/thumbnailPhoto?api-version=1.6
whereas in the SpringBoot AD example, the AccessToken returned from exactly the same call is of the form:
AQABAAAAAADXzZ3ifr-GRbDT....
and If I use that in exactly the same way to try to retrieve the user's profile pic, I get a 401 Unauthorized response
What's the reason for the difference in the form and use of these AccessTokens?
What's the reason for the difference in the form and use of these AccessTokens?
I assume that you got the access token is authorization_code not the bearer token.
As Rohit Saigal mentioned that you could use JWT.IO or JWT.MS to check that.
If we want to get the access token for Azure AD graph we could use the follow code to do that.
public String index(Model model, OAuth2AuthenticationToken authentication) {
...
DefaultOidcUser user = (DefaultOidcUser)authentication.getPrincipal();
String accessToken = user.getIdToken().getTokenValue();
...
}
Then we could use the access token to access the Azure AD graph api if you have assiged corrosponding permission.

How to get an access token using a refresh token in Java?

I am currently implementing Contact Application using Google Contact API in Java. I have completed steps of authorization and obtained an access token and a refresh token.
Now I have the CLIENT_ID , CLIENT_SECRET AND REFRESH_TOKEN with me . But the access token is getting expired within an hour.
Can someone tell how to automatically generate an access token using a refresh token in Java?
You can use Google OAuth2 client library for getting a new access token using a refresh token.
Here is my code for getting a new access token:
public TokenResponse refreshAccessToken(String refreshToken) throws IOException {
TokenResponse response = new GoogleRefreshTokenRequest(
new NetHttpTransport(),
new JacksonFactory(),
refreshToken,
"your clientId",
"your clientSecret")
.execute();
System.out.println("Access token: " + response.getAccessToken());
return response;
}
For more information read the official Google API guide:
OAuth 2.0 and the Google OAuth Client Library for Java
I have implemented this scenario in two ways. Not sure they are the best or not but works well for me.
In both cases you have to store the refresh token along with the email id of the user. Then you have to make a HTTP request in the below format.
POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
client_id=**<your_client_id>**&
client_secret=**<your_client_secret>**&
refresh_token=**<refresh_token>**&
grant_type=refresh_token
It will return the access_token and expires_in
Source
Now the question is how and when to do the http request. So for that I have two ways.
1st one
Store the emailid,refresh token, access token and the current time+3600 seconds. In your database you can schedule to check the expire time in every 5 min and if current time of any user is going to reach(before 5 or 10 min) the expire time, get the refresh token and update the value for that particular user. And during api call just fetch the access token of the user.
2nd one
When user do login in your site, get the access token and current time+ 3600secs and store it in browser cookies. Now before doing any api call just check whether the current time(time when api call is done) is less than the expire time(stored in cookie). If its true then you can use the previous access token else get a new one and again update the cookie. Also you have to put another condition that if the cookie is not present at all then also you have to get new refresh token.

How to get access token using refresh token?

In my app we want to provide login with google. So i went throught the folowing Quickstart and created a sample extending it by setting access_type to offline. So that i can get refresh token as their will be background task that will perform operation on those account after a particular interval of time, example: saving starrred mail in some file on server for each user.
So i need to know:
How to save refresh token ? like save it in DB with userId or somthing or save whole credential object as few post i have seen use credential object
How to use refresh token to get accesstoken ?
When does refresh token expires?
Code reference will be very useful.
Thank you!!
1.You can save the refresh token in DB as like userId, you can get new access token by using the refresh token
2.You need to pass the Client Id, Client Secret and Refresh token to get the new access token
3.Refresh tokens are valid until the user revokes access.

Categories

Resources