Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the UserTokenProvider token expiration

We're working on a new ASP.NET MVC 4.1 app. We're hooking up the ASP.NET Identity stuff, and we're struggling with tokens for password reset and new invite. I can't seem to find a way to set the expiration time for the tokens that are generated, and it seems to be set at around 10 mins by default. We're using a EmailTokenProvider as the user token provider, because it seems to work well with the security stamp on the user.

How can we set the expiration for the tokens - ideally we'd like to set it differently for the invite Vs the reset password tokens.

Our user manager looks like this:

var manager = new UserManager<User, long>(new UserStore(new UserRepository()));
manager.UserValidator = new UserValidator<User, long>(manager) {AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true};
manager.UserTokenProvider = new EmailTokenProvider<User, long>();

When a user requests a reset password link we call

var token = await _userManager.GeneratePasswordResetTokenAsync(user.Id); to get the token, and pass that on to the user.

When a user is invited, we call:

var token = await _userManager.GenerateUserTokenAsync("FirstLogin", user.Id);

to get the token, and send.

like image 837
Matt Roberts Avatar asked Oct 02 '14 15:10

Matt Roberts


2 Answers

The default implementations of the token providers in 2.0 don't allow you to change the token expiration, this is something we are considering for identity 3.0.

like image 100
Hao Kung Avatar answered Oct 07 '22 22:10

Hao Kung


If I understand your question well, following could help:

    private static string CalculateToken(User user)
    {
        byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
        byte[] key = BitConverter.GetBytes(user.ID);
        string token = Convert.ToBase64String(time.Concat(key).ToArray());
        return token;
    }

And then:

   DateTime time = DateTime.FromBinary(BitConverter.ToInt64(data, 0));
   int id = BitConverter.ToInt32(data, 8);

   if (time< DateTime.UtcNow.AddMinutes(-10) || user.ID != id)
            {
                //too old or IDs not matching
            }
like image 29
Velusoid Avatar answered Oct 07 '22 23:10

Velusoid