Announcing RTM of ASP.NET Identity 2.0.0

Announcing RTM of ASP.NET Identity 2.0.0

Rate This

Today, we are releasing the final version of ASP.NET Identity 2.0. The main focus in this release was to add security and account management features as well as address feedback from the community.

Download this release

You can download ASP.NET Identity from the NuGet gallery. You can install or update to these packages through NuGet using the NuGet Package Manager Console, like this:

What’s in this release?

Following is the list of features and major issues that were fixed in 2.0.0.

Two-Factor Authentication

ASP.NET Identity now support two-factor authentication. Two-factor authentication provides an extra layer of security to your user accounts in the case where your password gets compromised. Most  websites protect their data by having a user create an account on their website with a username and password. Passwords are not very secure and sometimes users choose weak passwords which can lead to user accounts being compromised.

SMS is the preferred way of sending codes but you can also use email in case the user does not have access to their phone. You can extend and write your own providers such as QR code generators and use Authenticator apps on phones to validate them.

There is also protection for brute force attacks against the two factor codes. If a user enters incorrect codes for a specified amount of time then the user account will be locked out for a specified amount of time. These values are configurable.

To try out this feature, you can install ASP.NET Identity Samples NuGet package (in an Empty ASP.NET app) and follow the steps to configure and run the project.

Account Lockout

Provide a way to Lockout out the user if the user enters their password or two-factor codes incorrectly. The number of invalid attempts and the timespan for the users are locked out can be configured.  A developer can optionally turn off Account Lockout for certain user accounts should they need to.

Account Confirmation

The ASP.NET Identity system now supports Account Confirmation by confirming the email of the user. This is a fairly common scenario in most websites today where when you register for a new account on the website, you are required to confirm your email before you could do anything in the website. Email Confirmation is useful because it prevents bogus accounts from being created. This is extremely useful if you are using email as a method of communicating with the users of your website such as Forum sites, banking, ecommerce, social web sites.

Note: To send emails you can configure SMTP Server or use some of the popular email services such as SendGrid (http://sendgrid.com/windowsazure.html) which integrate nicely with Windows Azure and require no configuration on the application developer

In the sample project below, you need to hook up the Email service for sending emails. You will not be able to reset your password until you confirm your account

Password Reset

Password Reset is a feature where the user can reset their passwords if they have forgotten their password.

Security Stamp (Sign out everywhere)

Support a way to regenerate the Security Stamp for the user in cases when the User changes their password or any other security related information such as removing an associated login(such as Facebook, Google, Microsoft Account etc). This is needed to ensure that any tokens (cookies) generated with the old password are invalidated. In the sample project, if you change the users password then a new token is generated for the user and any previous tokens are invalidated.

This feature provides an extra layer of security to your application since when you change your password, you will be logged out where you have logged into this application. You can also extend this to Sign out from all places where you have logged in from. This sample shows how to do it.

You can configure this in Startup.Auth.cs by registering a CookieAuthenticationProvider as follows.

Code Snippet
  1. app.UseCookieAuthentication(newCookieAuthenticationOptions {
  2.                 AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
  3.                 LoginPath = newPathString("/Account/Login"),
  4.                 Provider = newCookieAuthenticationProvider {
  5.                     // Enables the application to validate the security stamp when the user logs in.
  6.                     // This is a security feature which is used when you change a password or add an external login to your account. 
  7.                     OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
  8.                         validateInterval: TimeSpan.FromMinutes(30),
  9.                         regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
  10.                 }
  11.             });

Make the type of Primary Key be extensible for Users and Roles

In 1.0 the type of PK for Users and Roles was strings. This means when the ASP.NET Identity system was persisted in Sql Server using Entity Framework, we were using nvarchar. There were lots of discussions around this default implementation on Stack Overflow and based on the incoming feedback, we have provided an extensibility hook where you can specify what should be the PK of your Users and Roles table. This extensibility hook is particularly useful if you are migrating your application and the application was storing UserIds are GUIDs or ints.

Since you are changing the type of PK for Users and Roles, you need to plug in the corresponding classes for Claims, Logins which take in the correct PK. Following is a snippet of code which shows how you can change the PK to be int

For a full working sample please see https://aspnet.codeplex.com/SourceControl/latest#Samples/Identity/ChangePK/readme.txt

 

Code Snippet
  1.  
  2. publicclassApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>
  3. {
  4. }
  5.  
  6. publicclassCustomRole : IdentityRole<int, CustomUserRole>
  7. {
  8.     public CustomRole() { }
  9.     public CustomRole(string name) { Name = name; }
  10. }
  11.  
  12. publicclassCustomUserRole : IdentityUserRole<int> { }
  13. publicclassCustomUserClaim : IdentityUserClaim<int> { }
  14. publicclassCustomUserLogin : IdentityUserLogin<int> { }
  15.  
  16. publicclassApplicationDbContext : IdentityDbContext<ApplicationUser, CustomRole, int, CustomUserLogin, CustomUserRole, CustomUserClaim>
  17. {
  18. }

 

 

Support IQueryable on Users and Roles

We have added support for IQueryable on UsersStore and RolesStore so you can easily get the list of Users and Roles.

For eg. the following code uses the IQueryable  and shows how you can get the list of Users from UserManager. You can do the same for getting list of Roles from RoleManager

 

Code Snippet
  1.  
  2. // GET: /Users/
  3. publicasyncTask<ActionResult> Index()
  4. {
  5.     return View(await UserManager.Users.ToListAsync());
  6. }

Delete User account

In 1.0, if you had to delete a User, you could not do it through the UserManager. We have fixed this issue in this release so you can do the following to delete a user

Code Snippet
  1. var result = await UserManager.DeleteAsync(user);

IdentityFactory Middleware/ CreatePerOwinContext

UserManager

You can use Factory implementation to get an instance of UserManager from the OWIN context. This pattern is similar to what we use for getting AuthenticationManager from OWIN context for SignIn and SignOut. This is a recommended way of getting an instance of UserManager per request for the application.

Following snippet of code shows how you can configure this middleware in StartupAuth.cs. This is in the sample project listed below.

 

Code Snippet
  1.  
  2. app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

Following snippet of code shows how you can get an instance of UserManager

Code Snippet
  1. HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

DbContext

ASP.NET Identity uses EntityFramework for persisting the Identity system in Sql Server. To do this the Identity System has a reference to the ApplicationDbContext. The DbContextFactory Middleware returns you an instance of the ApplicationDbContext per request which you can use in your application.

Following code shows how you can configure it in StartupAuth.cs. The code for this middleware is in the sample project.

Code Snippet
  1. app.CreatePerOwinContext(ApplicationDbContext.Create);

Indexing on Username

In ASP.NET Identity Entity Framework implementation, we have added a unique index on the Username using the new IndexAttribute in EF 6.1.0. We did this to ensure that Usernames are always unique and there was no race condition in which you could end up with duplicate usernames.

Enhanced Password Validator

The password validator that was shipped in ASP.NET Identity 1.0 was a fairly basic password validator which was only validating the minimum length. There is a new password validator which gives you more control over the complexity of the password. Please note that even if you turn on all the settings in this password, we do encourage you to enable two-factor authentication for the user accounts.

Code Snippet
  1. // Configure validation logic for passwords
  2.             manager.PasswordValidator = new PasswordValidator
  3.             {
  4.                 RequiredLength = 6,
  5.                 RequireNonLetterOrDigit = true,
  6.                 RequireDigit = true,
  7.                 RequireLowercase = true,
  8.                 RequireUppercase = true,
  9.             };

You can also add Password policies as per your own requirements. The following sample shows you how you can extend Identity for this scenario. https://aspnet.codeplex.com/SourceControl/latest#Samples/Identity/Identity-PasswordPolicy/Identity-PasswordPolicy/Readme.txt

ASP.NET Identity Samples NuGet package

We are releasing a Samples NuGet package to make it easier to install samples for ASP.NET Identity. This is a sample ASP.NET MVC application. Please modify the code to suit your application before you deploy this in production. The sample should be installed in an Empty ASP.NET application.

Following are the features in this samples package

    • Initialize ASP.NET Identity to create an Admin user and Admin role.
      • Since ASP.NET Identity is Entity Framework based in this sample, you can use the existing methods of initializing the database as you would have done in EF.
    • Configure user and password validation.
    • Register a user and login using username and password
    • Login using a social account such as Facebook, Twitter, Google, Microsoft account etc.
    • Basic User management
      • Do Create, Update, List and Delete Users. Assign a Role to a new user.
    • Basic Role management
      • Do Create, Update, List and Delete Roles.
    • Account Confirmation by confirming email.
    • Password Reset
    • Two-Factor authentication
    • Account Lockout
    • Security Stamp (Sign out everywhere)
    • Configure the Db context, UserManager and RoleManager  using IdentityFactory Middleware/ PerOwinContext.
    • The AccountController has been split into Account and Manage controller. This was done to simplify the account management code.

The sample is still in preview since we are still working on improving the sample and fixing issues with it but it is in a state where you can easily see how to add ASP.NET Identity features in an application.

Entity Framework 6.1.0

ASP.NET Identity 2.0.0 depends upon Entity Framework 6.1.0 which was also released earlier in the week. For more details please read this announcement post.

List of bugs fixed

You can look at all the bugs that were fixed in this release by clicking this link.

Samples/ Documentation

Known Issues/ Change list

Migrating from ASP.NET Identity 1.0 to 2.0.0

If you are migrating from ASP.NET Identity 1.0 to 2.0.0, then please refer to this article on how you can use Entity Framework Code First migrations to migrate your database http://blogs.msdn.com/b/webdev/archive/2013/12/20/updating-asp-net-applications-from-asp-net-identity-1-0-to-2-0-0-alpha1.aspx

This article is based on migrating to ASP.NET Identity 2.0.0-alpha1 but the same steps apply to ASP.NET Identity 2.0.0

Following are some changes to be aware of while migrating

    • The migrations adding the missing columns in the AspNetUsers table. One of the columns is ‘LockoutEnabled’ which is set to false by default. This means that for existing user accounts Account Lockout will not be enabled. To enable Account Lockout for existing users you need to set it to true  by setting the ‘defaultvalue:true’ in the migration code.
    • In Identity 2.0 we changed the IdentityDbContext to handle generic User types differently. You will not see the discriminator column which is because the IdentityDbContext now works with ‘ApplicationUser’ instead of the generic ‘IdentityUser’. For apps that have more than one types deriving from IdentityUser, they need to change their DbContext to callout all the derived classes explicitly. For eg.
Code Snippet
  1. publicclassApplicationDbContext : IdentityDbContext<IdentityUser>
  2. {
  3. public ApplicationDbContext()
  4. : base("DefaultConnection", false)
  5. {
  6. }
  7.  
  8. protectedoverridevoid OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
  9. {
  10. base.OnModelCreating(modelBuilder);
  11. modelBuilder.Entity<ApplicationUser>();
  12. modelBuilder.Entity<FooUser>();
  13. }
  14. }

Migrating from ASP.NET Identity 2.0.0-Beta1 to 2.0.0

Following are the changes you will have to make to your application if you are upgrading from 2.0.0-Beta1 to 2.0.0 of Identity.

    • We have added Account Lockout feature, which is new 2.0.0 RTM
    • The GenerateTwoFactorAuthAsync generates the two factor auth only. The users need to explicitly call ‘NotifyTwoFactorTokenAsync’ to send the code.
    • While migrating data the EF migrations may add ‘CreateIndex’ for existing indices.

Give feedback and get support

    • If you find any bugs please open them at our Codeplex Site where we track all our bugs https://aspnetidentity.codeplex.com/
    • If you want to discuss these features or have questions, please discuss them on Stack Overflow and use the following tag “asp.net-identity”

Thank You for trying out the previews and your feedback for ASP.NET Identity. Please let us know your feedback around ASP.NET Identity

Leave a Comment
  • Please add 3 and 8 and type the answer here:
  • Post
  • Can't wait for the article on migrating from SimpleMembership to Identity 2.0. I see that it is already in progress (aspnet.codeplex.com/.../latest), but since I am the sole developer at my company, I generally wait for things to be well-baked before I go forward with them to limit potential pitfalls/errors.

    Any idea when we can expect it?

  • The sample is ready so you can use it as it is. You basically have 2 choices. Do you want to migrate the schema to Identity. if you can then I would recommend this option as future updated to Identity will be easier. If you cannot change your schema then you can plug in your schema into Identity, We have both the samples checked in as you noticed

  • So, will ASP.NET template in VS2013 be updated to use these whole new packages by default?

  • "Following are the changes you will have to make to your application if you are upgrading from 2.0.0-Beta1 to 2.0.0 of Identity."

    I notice that GetPasswordResetTokenAsync and GetEmailConfirmationTokenAsync extension methods are now called GeneratePasswordResetTokenAsync and GenerateEmailConfirmationTokenAsync. Maybe I'm upgrading from an earlier package.

    "We have added Account Lockout feature, which is new 2.0.0 RTM"

    Is there anything we need to do take advantage of this?

  • We've just started to implement v2.0.0-Beta1 and now the RTM version has been released :)

    These short deployment cycles are very impressive - thank you!

  • Can the SecurityStampValidator be used to ensure that a logged in user are "refreshed" if given a new role? Current in V1 you have to signout a user and then sign-in to enable a new role.

    Looking good. Thanks.

  • Hello,

    I am so happy with the new Identity 2.0.0 Release, but i got two migrations issues.

    So here you are two questions :

    1) First incident : Migration in VS2013 .NET 4.5.1 From Identity 1.0.0 to 2.0.0 on SQL Azure :

    a) from Package Manager Console in VS : update-package

    b) clean solution

    c)add-migration Identity2 -verbose

    Error message about ApplicationDbContext Constructor and a Boolean.

    I'am at the beginning of a small project, so i've suppressed "Migrations" Folder from code-source and "AspNet*" tables from SQL Azure: i need to publish soon and can't spend time.

    I need Account Confirmation and Password Recovery too.

    Then :

    a) enable-migrations : ok

    b) add-migration initial : ok

    c) update-database -verbose : ok

    Now when i start the MVC5 Site, the error message is :

    "Unable to determine the provider name for provider factory of type 'System.Data.SqlClient.SqlClientFactory'. Make sure that the ADO.NET provider is installed or registered in the application config. ".

    I have made search on the web about this, but it's early on Identity 2.0.0. Release.

    Question 1/2 : Might you help me on this point ?

  • Post 2 Question 2

    2) I have created a new solution from Visual Studio 2013, a Web Project with MVC Template only and Individual Accounts selected.

    I have used 4 commands with success :

    Install-Package Microsoft.AspNet.Identity.EntityFramework –Version 2.0.0

    Install-Package Microsoft.AspNet.Identity.Core -Version 2.0.0

    Install-Package Microsoft.AspNet.Identity.OWIN -Version 2.0.0

    Install-Package Microsoft.AspNet.Identity.Samples -Version 2.0.0-beta2 –Pre

    Last Package ask me about overwriting files, i have said overwrite all.

    I have manually change in the project properties .NET4.5 to .NET4.5.1.

    When i start debugging the sample solution throw an exception, shown bellow.

    Question 2/2 : Which of Connexion Strings with  name="DefaultConnection" may i keep / delete : line 12 or line 13 ?  

    Erreur du serveur dans l'application '/'.

    Erreur de configuration

     Description : Une erreur s'est produite lors du traitement d'un fichier de configuration requis pour répondre à cette demande. Veuillez consulter ci-dessous les détails relatifs à l'erreur en question, puis modifier votre fichier de configuration de manière appropriée.

    Message d'erreur de l'analyseur: L'entrée 'DefaultConnection' a déjà été ajoutée.

    Erreur source:

    Ligne 11 :   <connectionStrings>

    Ligne 12 :     <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-IdentitySample-20140321033828.mdf;Initial Catalog=aspnet-IdentitySample-20140321033828;Integrated Security=True" providerName="System.Data.SqlClient"/>

    Ligne 13 :     <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=IdentitySample-1-14;Integrated Security=SSPI" providerName="System.Data.SqlClient"/>

    Ligne 14 :   </connectionStrings>

    Ligne 15 :   <appSettings>

    Fichier source :  E:\fro.codeplex\IdentitySample\IdentitySample\web.config    Ligne :  13

    Informations sur la version : Version Microsoft .NET Framework :4.0.30319; Version ASP.NET :4.0.30319.34009

  • Post 2 - Question 2

    2) I have created a new solution from Visual Studio 2013, a Web Project with MVC Template only and Individual Accounts selected.

    I have used 4 commands with success :

    Install-Package Microsoft.AspNet.Identity.EntityFramework –Version 2.0.0

    Install-Package Microsoft.AspNet.Identity.Core -Version 2.0.0

    Install-Package Microsoft.AspNet.Identity.OWIN -Version 2.0.0

    Install-Package Microsoft.AspNet.Identity.Samples -Version 2.0.0-beta2 –Pre

    Last Package ask me about overwriting files, i have said overwrite all.

    I have manually change in the project properties .NET4.5 to .NET4.5.1.

    When i start debugging the sample solution throw an exception, shown bellow.

    Question 2/2 : Which of Connexion Strings with  name="DefaultConnection" may i keep / delete : line 12 or line 13 ?  

    Erreur du serveur dans l'application '/'.

    Erreur de configuration

     Description : Une erreur s'est produite lors du traitement d'un fichier de configuration requis pour répondre à cette demande. Veuillez consulter ci-dessous les détails relatifs à l'erreur en question, puis modifier votre fichier de configuration de manière appropriée.

    Message d'erreur de l'analyseur: L'entrée 'DefaultConnection' a déjà été ajoutée.

    Erreur source:

    Ligne 11 :   <connectionStrings>

    Ligne 12 :     <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-IdentitySample-20140321033828.mdf;Initial Catalog=aspnet-IdentitySample-20140321033828;Integrated Security=True" providerName="System.Data.SqlClient"/>

    Ligne 13 :     <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=IdentitySample-1-14;Integrated Security=SSPI" providerName="System.Data.SqlClient"/>

    Ligne 14 :   </connectionStrings>

    Ligne 15 :   <appSettings>

    Fichier source :  E:\fro.codeplex\IdentitySample\IdentitySample\web.config    Ligne :  13

    Informations sur la version : Version Microsoft .NET Framework :4.0.30319; Version ASP.NET :4.0.30319.34009

  • Any suggestions for this question ->

    stackoverflow.com/.../using-ioc-container-with-identityfactory-middleware

  • @Vindberg  no the security stamp is only used when you change any security info for your account such as password. When you change Roles you need to refresh the claims for user and you need to regenerate the cookie.

  • @Maximilian Haru Raditya  yes the templates will be updated in VS 2013 Update2 with these package versions.

  • @ta.speot.is  your application code needs to do the actual operation of locking out the user account. Please refer to the samples package on how to do it.

  • @Francois Rossello please install the samples NuGet package in an Empty ASP.NET application only since the sample application brings in MVC as well

  • I have installed Microsoft.AspNet.Identity.Samples in an Empty ASP.NET Web Application : it solved question 2.

    Thanks.

    For Question 1 : From Microsoft.AspNet.Identity 1.0.0 to 2.0.0 Error Message:

    "Unable to determine the provider name for provider factory of type 'System.Data.SqlClient.SqlClientFactory'. Make sure that the ADO.NET provider is installed or registered in the application config. ".

    It's because the source code need to be changed too, following the files from package samples.

    Where to start in your MVC solution ?

    1)  Key was added in Web.Config :

    <appSettings>

       <add key="owin:AppStartup" value="IdentitySample.Startup,IdentitySample" />

    2) The file Startup.Auth.cs completely changed.

    From this file, by following the missing references,  our migration should be completed.

    I'm working on that point.

Page 1 of 8 (113 items) 12345»