-1

Here i have code which generate token valid for 24 hours but i am looking for a logic which generate token number will be valid for 5 minutes. i search google but found no idea. so please some one share any idea would be appreciated. thanks

public static string GenerateToken()
{
    int month = DateTime.Now.Month;
    int day = DateTime.Now.Day;
    string token = ((day * 100 + month) * 700 + day * 13).ToString();
    return token;
}
Indi_Rain
  • 179
  • 5
  • 17

2 Answers2

1

If you use identity. You can implement this

using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
...   
public class SomeTokenAuthenticationService : IAuthenticateService
{
    private readonly TokenManagement _tokenManagement;
 
    public SomeTokenAuthenticationService(IOptions<TokenManagement> tokenManagement)
        {
            _tokenManagement = tokenManagement.Value;
        }
    
public string GenerateToken(ClaimsIdentity identity){
                var now = DateTime.UtcNow;
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenManagement.Secret));
                var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
        
                var jwtToken = new JwtSecurityToken(
                    _tokenManagement.Issuer,
                    _tokenManagement.Audience,
                    notBefore:now,
                    claims:identity.Claims,
                    expires: DateTime.Now.AddMinutes(_tokenManagement.AccessExpiration),
                    signingCredentials: credentials
                );
                var tokenjwt = new JwtSecurityTokenHandler().WriteToken(jwtToken);
        
                return $"Bearer {tokenjwt}";
            }}

also you need to add an option in appsettings.Development.json

"tokenManagement": {
    "secret": "Secret : in the 1eujsjjdjodjdjodfjodjojofjfdjdj 1234567891",
    "issuer": "test.user",
    "audience": "SampleAudience",
    "accessExpiration": 30,//minutes
    "refreshExpiration": 60
  }
1

This may not be the kind of implementation you're looking for, but take a look at this answer.

Excerpt:

Basic example of creating a unique token containing a time stamp:

byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
byte[] key = Guid.NewGuid().ToByteArray();
string token = Convert.ToBase64String(time.Concat(key).ToArray());

To decode the token to get the creation time:

byte[] tokenByteArray = Convert.FromBase64String(token);
DateTime when = DateTime.FromBinary(BitConverter.ToInt64(tokenByteArray, 0));
if (when < DateTime.UtcNow.AddMinutes(-5)) {
  // too old
}

(I changed the decode section to match your requirement for a 5 minute token invalidation, and changed the original "data" variable to "tokenByteArray" for clarity.)


Clarifications in response to comment request

Drilling down into why we use BitConverter.ToInt64(tokenByteArray, 0):

This whole implementation relies on that final deserialization operation which allows us to rebuild a copy of the original DateTime object that we started with.

This rebuilding / deserialization is accomplished by calling the static DateTime.FromBinary() method, which takes a 64-bit signed integer (or long data type) as its parameter.

Since we originally converted our DateTime object down into a byte[], we need to deserialize the string token that we generated to extract our DateTime value. And seeing that DateTime.FromBinary() requires a 64-bit signed integer parameter, we need to convert our string token's byte[] by calling BitConverter.ToInt64(tokenByteArray, 0) - (the 0 just denotes where in the array to start converting).

Now we just feed the converted 64-bit integer into the DateTime.FromBinary() method, and we're done.

Example / Fiddle

Resources:

Tcraw
  • 274
  • 1
  • 11
  • i will check your code and let you know. thanks for the answer. – Indi_Rain Jul 08 '20 at 08:27
  • this line not clear `DateTime.FromBinary(BitConverter.ToInt64(data, 0));` please explain when you get time. – Indi_Rain Jul 08 '20 at 08:28
  • Sure - updated my answer with some more details and an example fiddle. – Tcraw Jul 08 '20 at 17:07
  • thank you sir for clarification. – Indi_Rain Jul 08 '20 at 17:29
  • How to validate this token ? this time checking logic not workig. `if (when < DateTime.UtcNow.AddMinutes(-5)) { // too old }` – Indi_Rain Jul 09 '20 at 16:09
  • I've updated my .NET Fiddle with a validation example. You can run any DateTime comparison operations that you want (not just "AddMinutes(-5)") against the DateTime you extracted from the token. – Tcraw Jul 09 '20 at 17:24