Renew/Extend JWT in API before it expires - c#

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!

Related

How to handle JWT Token expiry in web API without logging out?

When the token is generated by sending a HTTP request to web API & the user has started working on the application that generated token is used in a particular session of the application. If during any HTTP request from the application to web API if JWT token expires WEB API won't return data. How is this situation handled in the application without any misbehavior or without troubling the user how that request will be continued?
And even if we generate a refresh token how to continue with the same HTTP request without troubling the user?
(If we store the generated token in the database then we know the token is valid but expired)
Try this :
Write backend refresh token API and allow an authenticated user to refresh their JWT token
In Frontend before requesting the API call decode the user's current JWT token and check whether it is expired or not.
https://www.npmjs.com/package/jwt-decode
If the token expired call the refresh token API before the actual request.
If you are using Angular or React library then there is a mechanism called HTTP_interceptor
https://www.bezkoder.com/angular-12-refresh-token/
https://www.bezkoder.com/react-refresh-token/
We also give a refresh token to the user along with the token, which has no claim and only has a username and a long expiration date. Every time the token expires, the security part of the applicationlooks at the refresh token and issues a new token for that username. You can manage the issuance of program tokens by setting the refresh token lifetime

OAuth2 in memory token loss due to server application restart

I encountered this problem in test stage of my application. Client set expiration date of token for very long time (19 years or so), so we wouldn't request new token often during tests. But After a while it came out that token has already expired (after random time).
The problem was server application being restarted/updated, resulting in in-memory tokens lost and rendering my simple check for expires_in not working:
if (_currentToken.ExpirationDate < DateTime.Now.AddMinutes(1))
{
_currentToken = GetToken();
}
How would I secure such scenario? It might as well happen on production, but hopefully more rarely due to less application restarts and shorter token time. Unfortunately I don't have an access to server side authorization settings and tokens won't be persited in any storage.
I would like avoid calling some dummy action on server to check if it returns 401 unauthorized before every action.
IMO it's server side's responsibility to validate token and decide whether the request with token could access specific protected resources . So as #armagedescu suggested , just send the token when performing token request , server side will check the claims like expire time , issuer ... and also check the signature . If token is expired , it will return 401 status code , and the OAuth 2.0 bearer token spec adds error, error_description, and error_uri attributes to the WWW-Authenticate header for reporting additional error information :
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example",
error="invalid_token",
error_description="The access token expired"
Then on client side you can check the errors , and refresh access token to perform another token request .

.NET Core API - does the middleware set the JWT bearer token in the header?

I've got all the code working to generate the JWT and I've wired up my ConfigureServices with the proper config code but I'm not seeing the header actually get set.
I assumed that the middleware would do this for you but maybe not, is it up to me to return the token from the login method of my controller and the client to then take it and set the header for subsequent requests?
No it does not.
The way it works is that you send your login credentials to a login server. In most cases its the same but in more secure applications this won't be the case.
The server then authenticates your credentials, creates a JWT token and sends that back to you.
You can then use that JWT in your header when making a request to the application server:
"Authorization":"Bearer xxxxx.yyyyy.zzzzz"
This needs to be done with every call to the server because the point of JWT is that it is stateless, meaning the server does not save the data at all. Instead in reads the JWT token with every call and grants access/functionality based on that.

How to invalidate or destroy jwt default token as external bearer in c#?

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.

OpenIdConnect token renewal

We have an MVC application that uses IdentityServer4 as a STS. We have set the access_token and identity_token lifetime to four hours on the Client properties in the STS. We have also added the scope offline_access in our MVC client.
How do we refresh the access_token and/or the identity_token from the STS in the MVC client?
What could work, but I don't see this as a good solution is request a new token on every request. Should we keep track of this time in the MVC client and call something like: https://github.com/IdentityServer/IdentityServer4.Samples/blob/293622b8438d27f4c9c2574e43fe92a22560ac6b/Clients/src/MvcHybrid/Controllers/HomeController.cs#L46
Or is there some event that we can hook up to and request the new token(s)?
You don't refresh identity tokens - only access tokens.
There is no event - either refresh tokens pro-actively based on expiration time - or wait until the API returns a 401 and refresh lazily.

Categories

Resources