Skip to content

Using Identity in ASP.NET applications

cH40z-Lord edited this page Oct 8, 2014 · 3 revisions

Using Identity in ASP.NET vNext

Add Nightly NuGet Feed

You need to configure NuGet to use the feed that contains nightly builds.

  1. In Visual Studio select Tools –> NuGet Package Manager –> Package Manager Settings

Install Identity (and Providers)

To get Identity in your project you need to install the Microsoft.AspNet.Entity NuGet package from the nightly feed. To do this, you can add the following packages in your project.json file.

"Microsoft.AspNet.Identity.EntityFramework": "3.0.0-*",
"Microsoft.AspNet.Identity.Authentication": "3.0.0-*",
"Microsoft.AspNet.Security.Cookies": "1.0.0-*"

Register Identity, create user and SignIn

Define a User and register Identity services in Startup. Add Cookie Authentication to remember logged in users.

using System;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Routing;
using Microsoft.AspNet.Security.Cookies;
using Microsoft.Data.Entity;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;

namespace WebApplication47
{
    public class Startup
    {
        public void Configure(IBuilder app)
        {         
            // Setup configuration sources
            var configuration = new Configuration();
            configuration.AddJsonFile("config.json");
            configuration.AddEnvironmentVariables();

            // Set up application services
            app.UseServices(services =>
            {
                // Add EF services to the services container
                services.AddEntityFramework()
                    .AddSqlServer();

                // Configure DbContext
                services.SetupOptions<DbContextOptions>(options =>
                {
                    options.UseSqlServer(configuration.Get("Data:DefaultConnection:ConnectionString"));
                });
                
                // Add Identity services to the services container
                services.AddIdentitySqlServer<ApplicationDbContext, ApplicationUser>()
                    .AddAuthentication();

            });

            // Add cookie-based authentication to the request pipeline
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = ClaimsIdentityOptions.DefaultAuthenticationType,
                LoginPath = new PathString("/Account/Login"),
            });
        }
    }
}

Register a user and signin

In your controller you can create a user and signin using the following code

public class AccountController : Controller
{
    public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
    {
        UserManager = userManager;
        SignInManager = signInManager;
    }

    public UserManager<ApplicationUser> UserManager { get; private set; }
    public SignInManager<ApplicationUser> SignInManager { get; private set; }

    public async Task<IActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.UserName };
            var result = await UserManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                AddErrors(result);
            }
        }
    }
}