# ASP.NET Core Identity
1. ASP.NET Core Identity is a membership system.
2. It allows us to create, read, update and delete user accounts.
3. Supports account confirmation, authentication, authorisation, password recovery, two-factor authentication with SMS.
4. It also supports external login providers like Microsoft, Facebook, Google etc.
## Adding ASP.NET Core Identity Support in ASP.NET Core Application
1. Inherit from IdentityDbContext class
public class AppDbContext : IdentityDbContext
{
// Rest of the code
}
Your application DbContext class must inherit from IdentityDbContext class instead of DbContext class. This is required because IdentityDbContext provides all the DbSet properties needed to manage the identity tables in SQL Server.
2. If you go through the hierarchy chain of IdentityDbContext class, you will see it inherits from DbContext class. So this is the reason you do not have to explicitly inherit from DbContext class if your class is inheriting from IdentityDbContext class.
3. Configure ASP.NET Core Identity Services
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<AppDbContext>();
4. AddIdentity() method adds the default identity system configuration for the specified user and role types.
5. IdentityUser class is provided by ASP.NET core and contains properties for UserName, PasswordHash, Email etc. This is the class that is used by default by the ASP.NET Core Identity framework to manage registered users of your application.
6. If you want store additional information about the registered users like their Gender, City etc. Create a custom class that derives from IdentityUser. In this custom class add the additional properties you need and then plug-in this class instead of the built-in IdentityUser class.
7. Similarly, IdentityRole is also a builtin class provided by ASP.NET Core Identity and contains Role information.
8. We want to store and retrieve User and Role information of the registered users using EntityFrameWork Core from the underlying SQL Server database. We specify this using AddEntityFrameworkStores<AppDbContext>() passing our application DbContext class as the generic argument.
9. Add Authentication middleware to the request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseStatusCodePagesWithReExecute("/Error/{0}");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
}
10. We want to be able to authenticate users before the request reaches the MVC middleware. So it's important we add authentication middleware before the MVC middleware in the request processing pipeline.
11. Add Identity Migration
## UserManager & SignInManager class
1. UserManager
- CreateAsync, DeleteAsync, UpdateAsync
2. SignInManager
- SignInAsync, SignOutAsync, IsSignedIn
## ASP.NET Core IdentityOptions
In this example, we are using the IdentityOptions object to configure PasswordOptions. We could also use this IdentityOptions object to configure
UserOptions
SignInOptions
LockoutOptions
TokenOptions
StoreOptions
ClaimsIdentityOptions
## Authentication & Authorization
1. Use [Authorize] attribute to apply secure endpoints
2. Use [AllowAnonymous] to provide anonymous access
### Possible Authorization based attributes
1. [Authorize(Roles = "Administrator")]
2. [Authorize(Roles = "Administrator,User")]
### Show hide menu based on role
@if (SignInManager.IsSignedIn(User) && User.IsInRole("Admin"))
{
<li class="nav-item">
<a class="nav-link" asp-controller="Administration" asp-action="ListRoles">
Manage Roles
</a>
</li>
}
## To check if the user is signedin, inject ASP.NET Core SignInManager service
@using Microsoft.AspNetCore.Identity
@inject SignInManager<ApplicationUser> SignInManager
@if (SignInManager.IsSignedIn(User) && User.IsInRole("Admin"))
{
}
OR
@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService authorizationService;
@if ((await authorizationService.AuthorizeAsync(User, "EditRolePolicy")).Succeeded)
{
<a asp-controller="Administration" asp-action="EditRole"
asp-route-id="@role.Id" class="btn btn-primary">
Edit
</a>
}