Asp Identity 2 - Change Expiry Time for Mobile Tok

2019-08-16 19:15发布

问题:

I have the following code that ensures the Token lifetime span for email verification tokens expire after 14 days :-

if (Startup.DataProtectionProvider != null)
            {
                IDataProtector dataProtector = Startup.DataProtectionProvider.Create("ASP.NET Identity");

                this.UserTokenProvider = new DataProtectorTokenProvider<IdentityUser, Guid>(dataProtector)
                {
                    TokenLifespan = TimeSpan.FromDays(14)
                };
            }

In a different area of my app, I'm using mobile phone number tokens by calling the GenerateChangePhoneNumberTokenAsync(userId, phoneNumber) method of the ASP.Identity ApplicationUserManager.

The problem is that the mobile tokens are expiring after 15 minutes.

How do i change the lifetime of the mobile tokens?

回答1:

You need to override

Microsoft.AspNet.Identity.UserManager.GenerateChangePhoneNumberTokenAsync

To do so please have a look here and here how to extend the UserManager first.

In GenerateChangePhoneNumberTokenAsync you need to use a custom Rfc6238AuthenticationService which has call to GenerateCode with timeStep parameter

The GenerateChangePhoneNumberTokenAsync will look like this

public class ApplicationUserManager : UserManager<YourIdentityUser, int>
{
    public ApplicationUserManager(IUserSecurityStampStore<YourIdentityUser, Guid> store)
        : base(store)
    {
    }

    // *** some other code

    public override async Task<string> GenerateChangePhoneNumberTokenAsync(Guid userId, string phoneNumber)
    {
        var user = await FindByIdAsync(userId);
        var code = CustomRfc6238AuthenticationService.GenerateCode(user.SecurityStamp, phoneNumber, "optional modifier", TimeSpan.FromDays(14));
        return code;
    }
}

and the sample implementation of custom Rfc6238AuthenticationService can be found here