I am authenticating the client via JWT token. First of all, client sends a request to method A with its credentials. If client is valid, JWT token is send to the client. This token is valid for just 2 minutes. The client should send this token and some other
data to method B in order to complete the process. Now there is a change in the design. I have to add another method for cancel/confirm. Client should call this new method to finish the transaction. I think the client can not use the previous JWT
token because it is used in method B and expired. So is there a way to reuse the same token? Is this possible? Or what is the preferred or best practice in this situation? How can I implement a refresh token logic into my code?
Thank you.
Keep your friends close and your enemies even closer
This is the very common problem for Microserices architecure and it is handled through API getway pattern. All the token validation should be handled at the API gateway level. After token validation, request should be forwarded to a (micro)service , that
service can trust the request. If you have anything to update/fix/improve/add regarding token security, it's done in single one place.
I am using asp.net web api2 and creating JWT token as follows and it works OK. How can I implement a refresh token mechanism in my code? Would you please help?
Here is the handler:
internal class TokenValidationHandler : DelegatingHandler
{
private static bool TryRetrieveToken(HttpRequestMessage request, out string token)
{
token = null;
IEnumerable<string> authzHeaders;
if (!request.Headers.TryGetValues("Authorization", out authzHeaders) || authzHeaders.Count() > 1)
{
return false;
}
var bearerToken = authzHeaders.ElementAt(0);
token = bearerToken.StartsWith("Bearer ") ? bearerToken.Substring(7) : bearerToken;
return true;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpStatusCode statusCode;
string token;
//determine whether a jwt exists or not
if (!TryRetrieveToken(request, out token))
{
statusCode = HttpStatusCode.Unauthorized;
//allow requests with no token - whether a action method needs an authentication can be set with the claimsauthorization attribute
return base.SendAsync(request, cancellationToken);
}
try
{
const string sec = "zdRhpFvSSjdG9n7";
var now = DateTime.UtcNow;
var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
SecurityToken securityToken;
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
TokenValidationParameters validationParameters = new TokenValidationParameters()
{
ValidAudience = "http://111.111.111.111:1907/api/v3/token",
ValidIssuer = "http://111.111.111.111:1907/api/v3/token",
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
LifetimeValidator = this.LifetimeValidator,
IssuerSigningKey = securityKey
};
//extract and assign the user of the jwt
Thread.CurrentPrincipal = handler.ValidateToken(token, validationParameters, out securityToken);
HttpContext.Current.User = handler.ValidateToken(token, validationParameters, out securityToken);
return base.SendAsync(request, cancellationToken);
}
catch (SecurityTokenValidationException e)
{
statusCode = HttpStatusCode.Unauthorized;
}
catch (Exception ex)
{
statusCode = HttpStatusCode.InternalServerError;
}
return Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage(statusCode) { });
}
public bool LifetimeValidator(DateTime? notBefore, DateTime? expires, SecurityToken securityToken, TokenValidationParameters validationParameters)
{
if (expires != null)
{
if (DateTime.UtcNow < expires) return true;
}
return false;
}
}
Here is the token creation in the controller:
public static string createToken(string username)
{
//Set issued at date
DateTime issuedAt = DateTime.UtcNow;
//set the time when it expires
DateTime expires = DateTime.UtcNow.AddMinutes(2);
var tokenHandler = new JwtSecurityTokenHandler();
//create a identity and add claims to the user which we want to log in
ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, username)
});
const string sec = "zdRhpFvSSjdG9n7";
var now = DateTime.UtcNow;
var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);
//create the jwt
var token =
(JwtSecurityToken)
tokenHandler.CreateJwtSecurityToken(issuer: "http://111.111.111.111:1907/api/v3/token", audience: "http://111.111.111.111:1907/api/v3/token",
subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials);
var tokenString = tokenHandler.WriteToken(token);
return tokenString;
}
How can I create refresh token to my example?
Keep your friends close and your enemies even closer
Any ideas how can I add refresh token in my code? Or should I need refresh token in my scneario?
Here is my scenario:
In my database there is a users table which has user id, user name, hash, salt and password.
Client sends request to method A with user id and password which is provided to them
User id and password is checked if it is valid, access token created and send in response.
Client sends request to method B in order to complete the process with the given access token.
Now there is an other method (cancel-confim) comes into play.
In order to call this new method directly, the access token should not be expired right?
If access token is expired then client has to make a new request for access token and if the client is valid a brand new access token is provided. Since the resouce and aut server is the same, I think I don't need for refresh token mechanism right? I couldn't
see any benefit of refresh token in my senario.
Please share your ideas? I think I don't need refresh token, either way (refresh token or not) client has to send a request.
Keep your friends close and your enemies even closer
it all in your security requirements. normally to refresh a token, you call a refresh api with the old token, and get a new one. this refresh api, could refresh an expired token if it was not too old. if you don't want to renew expired, then the calling
app has two choices
1) always call method a to get a new token to use in a second call.
2) use a timer, and refresh the token before it's expired. it should handle that the refresh is denied, and call method a again before a calling another method.
I don't see the difference in terms of number of calls. I mean in my scenario, client should make a request with it's creneditals in order to get the access token. Then with this access token, client send request to cancel/confim method to complete the process.
So in my case there is no point to implement a refresh token logic. Am I right? Am I missing something?
Keep your friends close and your enemies even closer
the main use of a JWT, is when the caller does not have access to the username & password for each call, or the callee does not have access to the password for validation. if the caller will always have the users credentials, and the callee can always validate,
then basic authentication may make more sense.
you use a JWT to pass the user name and claims securely without including the password. the service can validate the token without needing the password (it just needs the shared encryption key). this is real common case with a single sign on server. You
could also use a JWT to cache the claims, if it is expensive to gather the claims.
I am using customer id and password for extra measure. I will give customer id and password to the client upfront. With JWT, how would I know who is who?
I am using customer id and password for extra measure. I will give customer id and password to the client upfront. With JWT, how would I know who is who?
How is it possible that you do not know the client making the request if the client provides a username and password which exists in your system?
"you use a JWT to pass the user name and claims securely without including the password."
A JWT (JSON Web Token) is the result of a successful authentication.
cenk1536
How to parse JWT and check the user name?
I recommend using the JWT API that comes with .NET. If you want to roll your own JWT parser then you must read the openly published specs.
It is very difficult to understand how it is possible that you are using a JWT and looking into a refresh token without understanding how JWTs work. Are you grabbing code from the Internet hoping something will magically work?
JWT passes information in clear text (base64 encoded), but has an encrypted signature that guarantees that the data is not modified. typically a trusted service creates the JWT, and other services use the signature to verify that it has not been tampered
with.
a JWT token is 3 base64 strings separated by "."s
<header>.<payload>.<signature>
to get the data its:
Func<string,string> Base64UrlDecode = s =>
{
var base64 = s.Replace('-','+').Replace('_','/');
return System.Text.ASCIIEncoding.ASCII.GetString(System.Convert.FromBase64String(base64.PadRight(base64.Length + base64.Length % 3, '=')));
};
var jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
+ ".eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ"
+ ".SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
var payload = Base64UrlDecode(jwt.Split('.')[1]);
Console.WriteLine(payload);
Member
527 Points
2729 Posts
Refresh JWT authentication token for multiple API calls?
May 12, 2019 06:43 PM|cenk1536|LINK
Hello guys,
I am authenticating the client via JWT token. First of all, client sends a request to method A with its credentials. If client is valid, JWT token is send to the client. This token is valid for just 2 minutes. The client should send this token and some other data to method B in order to complete the process. Now there is a change in the design. I have to add another method for cancel/confirm. Client should call this new method to finish the transaction. I think the client can not use the previous JWT token because it is used in method B and expired. So is there a way to reuse the same token? Is this possible? Or what is the preferred or best practice in this situation? How can I implement a refresh token logic into my code?
Thank you.
Participant
850 Points
492 Posts
Re: Refresh JWT authentication token for multiple API calls?
May 13, 2019 05:57 AM|AddWeb Solution|LINK
Hi,cenk1536
This is the very common problem for Microserices architecure and it is handled through API getway pattern. All the token validation should be handled at the API gateway level. After token validation, request should be forwarded to a (micro)service , that service can trust the request. If you have anything to update/fix/improve/add regarding token security, it's done in single one place.
Reference Link :
https://stackoverflow.com/questions/46308536/reusing-a-bearer-token-for-multiple-api-calls
Member
527 Points
2729 Posts
Re: Refresh JWT authentication token for multiple API calls?
May 13, 2019 06:29 AM|cenk1536|LINK
I am using asp.net web api2 and creating JWT token as follows and it works OK. How can I implement a refresh token mechanism in my code? Would you please help?
Here is the handler:
Here is the token creation in the controller:
How can I create refresh token to my example?
Member
527 Points
2729 Posts
Re: Refresh JWT authentication token for multiple API calls?
May 14, 2019 05:02 AM|cenk1536|LINK
Any ideas how can I add refresh token in my code? Or should I need refresh token in my scneario?
Here is my scenario:
Please share your ideas? I think I don't need refresh token, either way (refresh token or not) client has to send a request.
All-Star
58254 Points
15674 Posts
Re: Refresh JWT authentication token for multiple API calls?
May 15, 2019 01:01 AM|bruce (sqlwork.com)|LINK
it all in your security requirements. normally to refresh a token, you call a refresh api with the old token, and get a new one. this refresh api, could refresh an expired token if it was not too old. if you don't want to renew expired, then the calling app has two choices
1) always call method a to get a new token to use in a second call.
2) use a timer, and refresh the token before it's expired. it should handle that the refresh is denied, and call method a again before a calling another method.
Member
527 Points
2729 Posts
Re: Refresh JWT authentication token for multiple API calls?
May 16, 2019 05:22 AM|cenk1536|LINK
I don't see the difference in terms of number of calls. I mean in my scenario, client should make a request with it's creneditals in order to get the access token. Then with this access token, client send request to cancel/confim method to complete the process. So in my case there is no point to implement a refresh token logic. Am I right? Am I missing something?
All-Star
58254 Points
15674 Posts
Re: Refresh JWT authentication token for multiple API calls?
May 16, 2019 04:14 PM|bruce (sqlwork.com)|LINK
the main use of a JWT, is when the caller does not have access to the username & password for each call, or the callee does not have access to the password for validation. if the caller will always have the users credentials, and the callee can always validate, then basic authentication may make more sense.
you use a JWT to pass the user name and claims securely without including the password. the service can validate the token without needing the password (it just needs the shared encryption key). this is real common case with a single sign on server. You could also use a JWT to cache the claims, if it is expensive to gather the claims.
Member
527 Points
2729 Posts
Re: Refresh JWT authentication token for multiple API calls?
May 16, 2019 06:48 PM|cenk1536|LINK
I am using customer id and password for extra measure. I will give customer id and password to the client upfront. With JWT, how would I know who is who?
In my payload I couldn't see password:
All-Star
53081 Points
23652 Posts
Re: Refresh JWT authentication token for multiple API calls?
May 16, 2019 07:08 PM|mgebhard|LINK
How is it possible that you do not know the client making the request if the client provides a username and password which exists in your system?
Member
527 Points
2729 Posts
Re: Refresh JWT authentication token for multiple API calls?
May 16, 2019 07:40 PM|cenk1536|LINK
my bad sorry, I thought password is included.
"you use a JWT to pass the user name and claims securely without including the password."
How to parse JWT and check the user name?
All-Star
53081 Points
23652 Posts
Re: Refresh JWT authentication token for multiple API calls?
May 16, 2019 07:53 PM|mgebhard|LINK
A JWT (JSON Web Token) is the result of a successful authentication.
I recommend using the JWT API that comes with .NET. If you want to roll your own JWT parser then you must read the openly published specs.
It is very difficult to understand how it is possible that you are using a JWT and looking into a refresh token without understanding how JWTs work. Are you grabbing code from the Internet hoping something will magically work?
https://jwt.io/introduction/
https://jwt.io/
All-Star
58254 Points
15674 Posts
Re: Refresh JWT authentication token for multiple API calls?
May 17, 2019 05:07 PM|bruce (sqlwork.com)|LINK
JWT passes information in clear text (base64 encoded), but has an encrypted signature that guarantees that the data is not modified. typically a trusted service creates the JWT, and other services use the signature to verify that it has not been tampered with.
a JWT token is 3 base64 strings separated by "."s
<header>.<payload>.<signature>
to get the data its:
of course you should validate the signature.
Member
527 Points
2729 Posts
Re: Refresh JWT authentication token for multiple API calls?
May 17, 2019 05:21 PM|cenk1536|LINK
thank you for all the responses. I will stick with my solution right now. I don't need refresh token which was my first concern.