如何为不同的用途使用不同的UserTokenProvider生命周期。身份2.0

时间:2014-10-07 09:22:49

标签: asp.net-mvc asp.net-identity-2

在IdentityConfig中,我们可以将UserTokenProvider设置为具有到期生命周期,该生命周期用于生成的每个令牌。 IdentityConfig在启动时运行..

                manager.UserTokenProvider =
                new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity")) 
                { TokenLifespan = TimeSpan.FromMinutes(60) };

但是在控制器中生成新令牌时是否可能:

var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

您可以为该用户/令牌使用不同的生命周期吗? 感谢名单

2 个答案:

答案 0 :(得分:1)

我知道这个问题很老但是因为它出现在搜索中:它目前无法实现。在codeplex(https://aspnetidentity.codeplex.com/workitem/2228

上有一个工作项

答案 1 :(得分:1)

我创建了一些扩展方法:

public static class UserManagerExtensions
{
    public static Task<string> GenerateAdjustableUserTokenAsync<TUser,TKey>(this UserManager<TUser, TKey> manager, TUser user, string purpose = null) 
        where TUser : class, IUser<TKey> 
        where TKey : IEquatable<TKey>
    {
        if (manager == null) throw new ArgumentNullException("manager");
        if (user == null) throw new ArgumentNullException("user");

        var dataProtector = new DpapiDataProtectionProvider("MyTokenizedApp").Create(purpose);
        var tokenProvider = new DataProtectorTokenProvider<TUser, TKey>(dataProtector);
        return tokenProvider.GenerateAsync(purpose, manager, user);
    }

    public static string GenerateAdjustableUserToken<TUser, TKey>(this UserManager<TUser, TKey> manager, TUser user, string purpose)
        where TUser : class, IUser<TKey>
        where TKey : IEquatable<TKey>
    {
        return GenerateAdjustableUserTokenAsync(manager, user, purpose).Result;
    }

    public static Task<bool> VerifyAdjustableUserTokenAsync<TUser, TKey>(this UserManager<TUser, TKey> manager, string token, TUser user, string purpose = null, TimeSpan? timeSpan = null)
        where TUser : class, IUser<TKey>
        where TKey : IEquatable<TKey>
    {
        if (manager == null) throw new ArgumentNullException("manager");
        if (user == null) throw new ArgumentNullException("user");
        if (token == null) throw new ArgumentNullException("token");

        var dataProtector = new DpapiDataProtectionProvider("MyTokenizedApp").Create(purpose);
        var tokenProvider = new DataProtectorTokenProvider<TUser, TKey>(dataProtector)
        {
            TokenLifespan = timeSpan ?? TimeSpan.FromDays(1)
        };
        return tokenProvider.ValidateAsync(purpose, token, manager, user);
    }

    public static bool VerifyAdjustableUserToken<TUser, TKey>(this UserManager<TUser, TKey> manager, string token, TUser user, string purpose = null, TimeSpan? timeSpan = null)
        where TUser : class, IUser<TKey>
        where TKey : IEquatable<TKey>
    {
        return VerifyAdjustableUserTokenAsync(manager, token, user, purpose, timeSpan).Result;
    }
}