The project I'm working on requires sending JWT token to the client via an endpoint when they login.
The JWT token returned is cached in cookie and any subsequent client requests will be sent with the token in the header that's obtained from the cookie.
The token needs to be renewed X minutes before it expires.
When the token is renewed, it will be sent back to the cookie and the client would get the new token from the cookie.
I wonder how I can intercept the token before it reaches the endpoints that are authorized by this token. Or is there any other way to do it? If not, how can I add customization to the JWT authentication handler? Thanks!
I’m writing a web api that will be called from a background service to fetch some data. After some research I decided to use a Json web token to achieve that but I’m still a bit confused regarding when a new token should be requested.
Let’s say I start up my service, I request a token, the token expires after 15 minutes, then after 20 minutes I make an api call with the expired token. I will get an unauthorized error or something.
My question is: How will the client know when to request a new token? Should it request a new one before every api call? Seems like I’m missing something. Maybe I should make the token permanent and store it in the database?
Thanks
The answer to this is slightly application specific, but the OAuth specification has a mechanism for "refresh tokens", which can be used to grant new "access tokens" (the token typically included on each API request), without having to send the user to the UI authentication process to have them re-authenticate. So, once you request an access token, you will receive a refresh token and an access token. This methodology allows access tokens to be used for much shorter time frames.
This can also be done without refresh tokens, but in those cases the access token timeout would likely be longer, and then you would request that the user re-authenticate through the usual OAuth UI process. Note that even when you do have refresh tokens, the refresh token can also be set to expire, in which would then require a user re-authentication through UI again.
In some API's you just make the API request as usual, and if you get a response that is defined by the API to be one that indicates the access token has expired, you can then issue an API call to refresh the token (or fully request a new one if that is expired, or you the API doesn't have refresh tokens), and then make the original API call again with the new access token.
The API can also have a response that includes the timeout or expiration date/time of the access token as well. Then, the client can avoid sending the initial API call first, and simply send the refresh token call first.
In implementing your API, you could likely use any of these methodologies.
Here's some general discussion on the OAuth spec website, to provide more depth:
https://www.oauth.com/oauth2-servers/making-authenticated-requests/
https://www.oauth.com/oauth2-servers/access-tokens/access-token-lifetime/
https://www.oauth.com/oauth2-servers/access-tokens/refreshing-access-tokens/
And also, here's an example from the Twitter API regarding response codes showing one of the access token expiration techniques (see the "Error Codes" section, under error code 89, which implies the token has expired and you need to get a new one):
https://developer.twitter.com/en/docs/basics/response-codes
Since your client is background service , you can use the Oauth2 Client Credential Flow . Your background service can request an access token using only its client credentials when the client is requesting access to the protected resources under its control.
With this flow , you does't need to care much about the token expires , if client sends an expired token to web api , web api validate the token and create token expires response to your service , your service check the status code/response , directly send a new token request to web api to get new access token , there is no need to use refresh token which uses in other flows .
The fact is that your harness should be prepared to request any token when getting an Unauthorized status code. What I do in test is to check the expiration datetime, if close enough I refresh or get a new token whatever applies to your Auth. Also when getting an unauthorized status code my code does a refresh once and keep a count. If I get another unauthorized code then I return a false or throw an exception after I log the error on the second try. This works fine for me.
I have been using Force.com Toolkit for .NET for long time. Recently one of a client has started complaining for session invalid issue. So I started digging up and found that I have to refresh token by calling TokenRefreshAsync for which I need to pass on refresh token which I get during authentication. But I am getting null refresh token from SF.
I have tried everything possible thing I found on the internet without any success. Perform requests on your behalf at any time (refresh_token, offline_access) is added in OAuth Scopes:
Refresh token expiry is set at 2 days:
This is the simple code I am using to authenticate:
var task = authClient.UsernamePasswordAsync(consumerKey, consumerSecret, username, password, callback);
task.Wait();
What am I missing here?
The Username-Password Oauth Flow does not provide a refresh token on Salesforce, regardless of scopes:
This OAuth authentication flow passes the user’s credentials back and forth. Use this authentication flow only when necessary. No refresh token is issued.
If you want a refresh token, you'll need to implement a different OAuth flow (preferable!), or eschew the refresh token and reauthenticate when your access token expires. The latter makes you vulnerable to credential and security token changes on the part of the authenticated user, however, which using a more suitable OAuth flow grants resilience against.
I am using web api and implemented default behavior for login i.e. endpoints using jwt authentication and now I am facing issue in invalidating or destroying jwt token as I want to implement logout functionality.
Can anyone suggest the logic for this situation how to deal with JWT tokens expiration?
Note: For login GrantResourceOwnerCredentials method is used as usual and it creates the token for authentication purpose.
Once you have issued your token it will be active until it expires.
If you need to perform a logout or 'invalidate' the token you will need to perform an extra step.
What you could do is store a SessionId (that is a guid) in the db on the User table. When a user logs in send the session id alongside the beader token. Store this session id in a cookie or in sessionStorage or whatever and send it up to the server with each request. Then you can have a filter applied globally to every action that checks the SessionId sent up from the client matches the SessionId stored in the database.
Then if you need to invalidate the token then store a new guid SessionId in the user table, when the next request comes it won't match and you can return a 401 response.
If you want to invalidate certain tokens, you need to store the tokens you give out in a database.
Then you check against those tokens when you validate the incoming token.
When you need to invalidate one, just delete it from the database.
I am using token based authentication (OAuth 2.0). If user is valid a token is generated successfully. All this is fine.
But there is Logout functionality. My question is not how to delete the token (its not possible).
But when I generated a token I had set an expiration time. Now if user wishes to logout all I am thinking to set the token expiration time to Date.now. So that if user tries to logon with the same token, he gets an access denied exception.
Something like this - https://api.facebook.com/restserver.php?method=auth.expireSession&format=json&access_token=<access_token>
Thanks.