Wednesday, June 12, 2019

Asp.net Core Continued

65 66 67 68 69 70 71

65 ASP.NET Core Identity
It is a membership system

Step 1 : Inherit from IdentityDbContext class instead of DB Context
public class AppDbContext : IdentityDbContext
{
    // Rest of the code
}
This is required because IdentityDbContext provides all the DbSet properties needed to manage the identity tables in SQL Server.

Step 2 : Configure ASP.NET Core Identity Services
In ConfigureServices() method of the Startup class, include the following line of code

services.AddIdentity<IdentityUser, IdentityRole>()
        .AddEntityFrameworkStores<AppDbContext>();

Step 3 : Add Authentication middleware to the request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseStaticFiles();   // already there
    app.UseAuthentication(); // Add this peice of code
    app.UseMvc(routes =>    // already there
}
 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.

Step 4 : Add Identity Migration
Add-Migration AddingIdentity

66. Register new user using asp.net core identity
only UI compnent being built

67. ASP.NET Core Identity UserManager and SignInManager
UserManager<IdentityUser> - CreateAsync, UpdateAsync, DeleteAsync, etc
SignInManager<IdentityUser> - SignInAsync, SignOutAsync, IsSignedIn, etc

UserManager<IdentityUser> class contains the required methods to manage users in the underlying data store
SignInManager<IdentityUser> class contains the required methods for users signin

Both UserManager and SignInManager services are injected into the AccountController using constructor injection
public class AccountController : Controller
    {
        private readonly UserManager<IdentityUser> userManager;             //created 2 private fields
        private readonly SignInManager<IdentityUser> signInManager;         //as above

        public AccountController(UserManager<IdentityUser> userManager,     // Constructor Injection
            SignInManager<IdentityUser> signInManager)
        {
            this.userManager = userManager;
            this.signInManager = signInManager;
        }

        [HttpGet]
        public IActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                // Copy data from RegisterViewModel to IdentityUser
                var user = new IdentityUser
                {
                    UserName = model.Email,
                    Email = model.Email
                };
                var result = await userManager.CreateAsync(user, model.Password); // Store user data in AspNetUsers database table
if (result.Succeeded)
                {
                    await signInManager.SignInAsync(user, isPersistent: false);  // SignIn the user
                    return RedirectToAction("index", "home");
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            return View(model);
        }
    }

68. ASP.NET core identity password complexity
We could do this by, using the Configure() method of the IServiceCollection interface in the 'ConfigureServices()' method of the Startup class

services.Configure<IdentityOptions>(options =>
{
    options.Password.RequiredLength = 10;
    options.Password.RequiredUniqueChars = 3;
    options.Password.RequireNonAlphanumeric = false;
});

OR

We could also do this while adding Identity services
services.AddIdentity<IdentityUser, IdentityRole>(options =>
{
    options.Password.RequiredLength = 10;
    options.Password.RequiredUniqueChars = 3;
    options.Password.RequireNonAlphanumeric = false;
})
.AddEntityFrameworkStores<AppDbContext>();

69. Show or hide login and logout links based on login status
a. Inject SignInManager in the view, so we could check if the user is signed-in

b. Check if a user is signed in
@if (SignInManager.IsSignedIn(User))
        {
            <li class="nav-item">
                <form method="post" asp-controller="account" asp-action="logout">
                    <button type="submit" style="width:auto"
                            class="nav-link btn btn-link py-0">
                        Logout @User.Identity.Name
                    </button>
                </form>
            </li>
        }

c. Write the code for logout
    [HttpPost]
    public async Task<IActionResult> Logout()
    {
        await signInManager.SignOutAsync();
        return RedirectToAction("index", "home");
    }

No comments:

Post a Comment

Asp.net Core Continued

65 66 67 68 69 70 71 65 ASP.NET Core Identity It is a membership system Step 1 : Inherit from IdentityDbContext class instead of ...