I have different login methods for mobile and web application in .net webapi identity backend. Both clients are using ssame authentication scheme(IdentityConstants.BearerScheme). But I want to change expirations time for my clients. For example for my mobile 14 days, for my web 1 day. Is there any way to change token expiration dynamically in method?
Login for web:
_signInManager.AuthenticationScheme = IdentityConstants.BearerScheme;
var result = await _signInManager.PasswordSignInAsync(loginForVisionRequest.Email, loginForVisionRequest.Password, isPersistent: false, lockoutOnFailure: true);
//make token expiration 14 days
if (!result.Succeeded)
{
return TypedResults.Problem("Unauthorized", statusCode: 401);
}
return TypedResults.Empty;
Login for mobile:
_signInManager.AuthenticationScheme = IdentityConstants.BearerScheme;
var result = await _signInManager.PasswordSignInAsync(loginForVisionRequest.Email, loginForVisionRequest.Password, isPersistent: false, lockoutOnFailure: true);
//make token validation 1 day
if (!result.Succeeded)
{
return TypedResults.Problem("Unauthorized", statusCode: 401);
}
return TypedResults.Empty;
I tried to use different schemes but I have to use BearerAuthentication but not JWT.
After some research, I did not find a way to dynamically set the expiration of a bearer token.
I did find that this is possible with cookies, as this answer to another question explains. Unfortunately the BearerTokenOptions Events class does not support the OnSigningIn
event the way is possible for cookies.
If this is something you really need, you'll have to implement your own middleware to verify whether a token is still valid. You could do this by adding a timestamp that indicates when the token expires into the token yourself.
Then implement your own middleware that checks whether or not the token is still valid with each request.
This way you can still "dynamically" set the token's expiration time depending on the user's platform. Which can be found in the UserAgent
as explained in this answer.