Refresh access_token via refresh_token in Keycloak - java

I need to make the user keep login in the system if the user's access_token get expired and user want to keep login. How can I get newly updated access_token with the use of refresh_token on Keycloak?
I am using vertx-auth for the auth implementation with Keycloak on vert.x. Is it possible to refresh access_token with vertx-auth or Keycloak's REST API itself? Or what will be another implementation of this?

keycloak has REST API for creating an access_token using refresh_token. It is a POST endpoint with application/x-www-form-urlencoded
Here is how it looks:
Method: POST
URL: https://keycloak.example.com/auth/realms/myrealm/protocol/openid-connect/token
Body type: x-www-form-urlencoded
Form fields:
client_id : <my-client-name>
grant_type : refresh_token
refresh_token: <my-refresh-token>
This will give you new access token using refresh token.
NOTE: if your refresh token is expired it will throw 400 exception in that you can make user login again.
Check out a sample in Postman, you can develop and corresponding API using this.

#maslick is correct you have to supply the client secret too, no need for authorization header in this case:
http://localhost:8080/auth/realms/{realm}/protocol/openid-connect/token
In case of expired refresh token it returns:
If you don't add the secret you get 401 unauthorized even though the refresh token is correct

I tried with 4.8.2.Final, it gives following unauthorized_client even with previous access token as 'Bearer'.
Then I tried with Basic YXBwLXByb3h5OnNlY3JldA== in Authorization header.
Then it worked, But still I'm not sure that I am doing right thing.

Extending Yogendra Mishra's answer. Note that
client_id and client_secret can also be sent in Authorization header.
Authorization: Basic ${Base64(<client_id>:<client_secret>)}
This works for both initial token call (without refresh token) and refresh token call to /openid-connect/token endpoint
Reference:
https://developer.okta.com/docs/reference/api/oidc/#client-secret

Related

Unable to get user info from OKTA with access token

I have valid access token from OKTA
when i call user info end point for user details i am getting 401 Unauthorised for the below POST request
https://*******.okta.com/oauth2/epros/v1/userinfo
Authorization : Bearer **
I have claims defined at OKTA for accesstoken as well
Any clue why for valid access token, i am getting 401?
Assuming you have checked your token is still valid, not expired revoked etc.
Your userinfo endpoint looks a little odd, where you have epros you would normally have the id of the authorization server.
For example https://*****.okta.com/oauth2/ausaew0e1C0brPuB80x6/v1/userinfo
You may have truncated that address as if that value is wrong you would get 400 bad request.
The correct endpoint will always be the value in the iss claim in the token plus /v1/userinfo, if you are sending the access token of one to another authorization server's userinfo you will get a 401 response.

How does server return JWT token to the client?

This is my first encounter with a JWT token and I'd like to know how is this token returned to the client after it's first created.
Should it come in the Authorization : Bearer header ?
Usually, it's the client that passes the token in Authorization : Bearer header on each request.
I'd like to know how does the server pass this token to the client after user has authenticated and the token gets created. Also in the same header? In a different header?
In my situation, the server will be generating the token not as a response but as part of the request.
For example:-
A user will login to a portal, then click on a link to an authorized application. The JWT containing user claims will be passed to the authorized application as part of the request.
What is the best approach here? GET or POST? Header (which)? Query string? POST body?
Thank you!
there is no standard for how to return JWT token to the client, however, check this URL, it answers your question
https://github.com/dwyl/hapi-auth-jwt2/issues/82#issuecomment-129873082
putting the JWT token in the Authorization header gives us flexibility to send an actual response in a web application. For a REST-only App/API you are free to send the JWT as the response body or a cookie. What matters is how the client stores the JWT and sends it back to the Server, which is done in the Authorization header (or Cookie or URL Token if you prefer) 👍
As for this existing in the "wild", I have not seen an example of the server sending an Authorisation header to the client, but there is nothing in the spec to suggest this is an anti-pattern.
see: http://self-issued.info/docs/draft-ietf-oauth-v2-bearer.html
If you want to stick to the guidelines you would do follow this example: http://self-issued.info/docs/draft-ietf-oauth-v2-bearer.html#ExAccTokResp
One may be interested to know that the OAuth 2.0 standard specifies the response body for that purpose:
5.1. Successful Response
The authorization server issues an access token and optional refresh
token, and constructs the response by adding the following parameters
to the entity-body of the HTTP response with a 200 (OK) status code:
access_token
REQUIRED. The access token issued by the authorization server.
[...]

How to authentication and authorization using JWT in SSO for microservices?

We are using spring API security in a spring boot application.
We have implemented two level of security which is page level and also API level. We support both login from our own application and SSO login. we also skiping two apis from authN ( api/login and /api/token)
I have few questions regarding the architecture.
Number 1:
We have our own login which will get input as userName and password for authentication and returns an access token.
How can I add SSO(Single Sign On) to this API?
Number 2:
How to persist the token and how to use the refresh token.
When the user get logged in, I will create an access token and a refresh token. The access token will be sent back to the UI and the refresh token will be in the DB/cache. When the user calls any API from his browser, he will send the access token with the ajax request, the filter validates the token and sends the responce after validating the token in the preAuthN service.
My question is, if the access token supposedly is expired, then how can I generate my new access token using the refresh token?
Solution 1:
once the server receives the access token, validate that and if the access token expired, from the server itself call /api/token to renew acess token and process the reques and send back the responce with the token
Solution 2:
Once the server receives the access token, validate that and if the access token expired, send the acknowledgement to the browser and the browser will handle it somehow to generate a new access token
Or are there any better solutions?

Spring Security Oauth2. Store refresh_token on server side

There is spring-security-oauth2 service with grant_type=password, refresh token.
I want to store refresh_token in java code and not send it to client via http(s). (why? - here)
So, 2 cases have to be handled:
1. do not send refresh_token in response
2. automatically insert refresh_token in request when in needed
1st can be done as in here
Question: how 2nd case can be done?
Usually, to get access token via refresh_token following request have to be sent:
POST: .../oaut/token?refresh_token=***&grant_type=refresh_token
I want to send
POST: .../oaut/token?access_token=***&grant_type=refresh_token
and then fetch refresh_token corresponding to access_token from some storage and add it as request parameter
Simple custom Spring Filter can help here. In particular OncePerRequestFilter.class [example]

Does it needs to pass username:password combination in any request with basic auth?

I confused with basic http authorization. It is needed to send every request to server with Authorization header or just first one and after that browser rember auth tokens like session id?
You have to send the Authorization header on each request. But for example Chrome remembers the auth tokens and sends it automatically on each request.
Using basic authentication, every request needs to have an Authorization HTTP header in the format:
Authorization: Basic <base64(username:password)>
where the username and password are concatenated using a colon (':') and the resulting string is base64 encoded.
If the Authorization header is not part of the request, or the credentials inside are not valid, the server should respond with an HTTP 401 Unauthorized response and include a HTTP header like:
WWW-Authenticate: Basic realm="myRealm"
Basic authentication is an implicit authentication scheme, so after the user enters valid credential, the browser will send them along with each page request.
For AJAX requests you'll need to attach this header from code. However, you really should not use basic authentication to protect an API, for a number of reasons:
You'd force the client to hold those credentials in code, where they can easily be stolen.
You must use HTTPS with basic authentication as base64 encoding gives no protection of the credentials at all.
Username/password combinations are usually valid much longer than an access token, thereby increasing the risk if they get stolen.
Password validation should be a slow process to mitigate brute force attacks, where token validation is just verifying a digital signature.
Having to send the username/password over the wire every time increases the attack surface for someone trying to break the encryption.
Better alternatives to protect web APIs are token based authentication schemes like OAuth2 or HMAC based authentication schemes like Hawk or AWS
Ya that's correct , so for first time when user logs in , his credentials are verified against some data , if correct , a auth token is generated.
Auth token is pretty much a self contained entity (which stores some data signed with a key)
this token gets stores at client side(usually along with a refresh token)
for all subsequent requests , this token is kept in Authorization header(Bearer+token)
When server receives this token , it decrypts it with the key , which it used earlier to sign that token. And uses that stored data
If that auth token is expired , refresh token comes into play.
some links to begin with
On a high level, how does OAuth 2 work?
and jwt.io to get the feel of tokens

Categories