How to implement a TokenProvider in ASP.NET Identity 1.1 nightly build?

21,460

Solution 1

The default token provider implementation is found in the Microsoft.Identity.Owin package:

/// <summary>
/// Token provider that uses a DataProtector to generate encrypted tokens
/// </summary>
public class DataProtectorTokenProvider : ITokenProvider {
    public DataProtectorTokenProvider(IDataProtector protector)

And you do something like this to wire one up using the default data protection provider from your OWIN IAppBuilder

IDataProtectionProvider provider = app.GetDataProtectionProvider();
if (provider != null)
{
    manager.PasswordResetTokens = new DataProtectorTokenProvider(provider.Create("PasswordReset"));
    manager.UserConfirmationTokens = new DataProtectorTokenProvider(provider.Create("ConfirmUser"));
}

Solution 2

If someone looking for solution under AspNet.Identity 2.0 beta1 version.

Only this need to be modified.

UserManager.UserTokenProvider = new DataProtectorTokenProvider
<SecurityUser, string>(provider.Create("UserToken")) 
as IUserTokenProvider<SecurityUser, string>;

PasswordResetTokens and UserConfirmationTokens is merged into UserTokenProvider property and token provider class is also modified.

Solution 3

Another way to do this (building on the other answers but simplifying it some) is to change Startup.Auth.cs so it looks similar to this:

public partial class Startup
{
    internal static IDataProtectionProvider DataProtectionProvider { get; private set; }

    public void ConfigureAuth(IAppBuilder app)
    {
        DataProtectionProvider = app.GetDataProtectionProvider();
    }
}

Then, modify the default constructor in AccountController.cs so that it looks similar to this:

 public AccountController()
     : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
 {
     if (Startup.DataProtectionProvider != null)
     {
         this.UserManager.PasswordResetTokens = new DataProtectorTokenProvider(Startup.DataProtectionProvider.Create("PasswordReset"));
         this.UserManager.UserConfirmationTokens = new DataProtectorTokenProvider(Startup.DataProtectionProvider.Create("ConfirmUser"));
     }
 }

Solution 4

Ok, answering my own question based on @hao-kung reply. First add static constructor and UserManagerFactory to Statrup class (startup.auth.cs)

public partial class Startup
{
    static Startup()
    {
        UserManagerFactory = () => new UserManager<IdentityUser>(new UserStore<IdentityUser>());
    }

    public static Func<UserManager<IdentityUser>> UserManagerFactory { get; set; }

    public void ConfigureAuth(IAppBuilder app)
    {
        var manager = UserManagerFactory();
        IDataProtectionProvider provider = app.GetDataProtectionProvider();
        if (provider != null)
        {
            manager.PasswordResetTokens = new DataProtectorTokenProvider(provider.Create("PasswordReset"));
            manager.UserConfirmationTokens = new DataProtectorTokenProvider(provider.Create("ConfirmUser"));
        }


        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
    }
}

Then init UserManager in the AccountController using that UserManagerFactory

public AccountController() : this(Startup.UserManagerFactory())
{
}

public AccountController(UserManager<IdentityUser> userManager)
{
    UserManager = userManager;
}

public UserManager<IdentityUser> UserManager { get; private set; }
Share:
21,460
graycrow
Author by

graycrow

Updated on July 09, 2022

Comments

  • graycrow
    graycrow almost 2 years

    I'm trying to implement password reset functionality with nightly build of ASP.NET Identity 1.1. There is a UserManager.GetPasswordResetToken method, but it throws an exception "No ITokenProvider is registered". Is there an built in token provider in ASP.NET Identity? If yes, how I can register it? If no, how I can implement one? Will be default Token Provider in the 1.1. release? And final question, is there an estimated 1.1 release date?

  • graycrow
    graycrow over 10 years
    Thank you, looks promising. Just one question: how can I access IAppBuilder app from the place where I initializing UserManager (for example, from AccountController)?
  • Scott Dorman
    Scott Dorman over 10 years
    Which nightly build is this in? I'm using the 1.1.0-alpha1-131024 (Prerelease) packages and I don't see a GetDataProtectionProvider method. If there is a default token provider why aren't the PasswordResetTokens and UserConfirmationTokens properties already initialized with it so we don't have to jump through these hoops to be able to use them? Unless you need to change something about how the tokens are generated, this should "just work" out of the box without any extra work required or (to me at least) there isn't really a point in creating a default provider.
  • Hao Kung
    Hao Kung over 10 years
    So the reason they are not part of Identity.Core and live in Identity.Owin is that Core cannot depend on Owin, and the default implementation comes from Owin. GetDataProtectionProvider lives in Microsoft.Owin.Security.DataProtection as an extension method off of IAppBuilder I believe.
  • Scott Dorman
    Scott Dorman over 10 years
    Found the method in the namespace you specified. I still think all of this should already be initialized out of the box. I shouldn't have to set any of this up unless I want to change how the token providers work.
  • PussInBoots
    PussInBoots about 10 years
    It appears that for the account confirmation / forgot password features in ASP.NET Identity 2.0 alpha you need to redesign all of your initialization code for UserManager etc. Just take a look in this sample MVC app aspnet.codeplex.com/SourceControl/latest Samples->Identity->Identity-PasswordPolicy and compare it to a default RTM MVC 5 app and you will see the difference. There is a huge difference in the initialization stuff (check Startup.Auth.cs for instance) and will have a big impact on any MVC application using ASP.NET Identity 1.0 (current RTM). Not so good!
  • Hao Kung
    Hao Kung about 10 years
    In general the old 1.0 style will work as well, our prescriptive guidance and default samples will just be doing things differently since some of the new 2.0 features require the initialization.
  • Pit Digger
    Pit Digger about 10 years
    Where does DataProtectorTokenProvider come from ?
  • Vikash Kumar
    Vikash Kumar about 10 years
    It comes from Microsoft.AspNet.Identity.Owin namespace.
  • Pit Digger
    Pit Digger about 10 years
    Nope its not there in it .
  • Vikash Kumar
    Vikash Kumar about 10 years
    I am not sure which version are you using. You can look this class link
  • masterwok
    masterwok almost 10 years
    How would someone set the TokenLifespan to be different if both PasswordResetTokens and UserConfirmation tokens are merged into UserTokenProvider?
  • Vikash Kumar
    Vikash Kumar almost 10 years
    Not sure if this facility is available. Codeplex
  • heymega
    heymega almost 10 years
    @jtsan The Token lifespan is a public property so you can set it before each call. new DataProtectorTokenProvider<ApplicationUser>(dataProtectionPr‌​ovider.Create("ASP.N‌​ET Identity")){ TokenLifespan = new TimeSpan() };
  • ManirajSS
    ManirajSS over 8 years
    what is GetDataProtectionProvider() method ?