find and solve || findandsolve.com
Please wait.....

Login and Registration using Identity in ASP.NET Core (.NET 5)

Login and Registration using Identity in ASP.NET Core (.NET 5)

In this .NET 5 Core MVC tutorial, I will implemented a complete authentication system with the help of Identity.UI.I will discuss how to create registration, login and logout functionalities in ASP.NET Core web applications using Identity. .NET Core Identity is an API that supports login functionality in ASP.NET Core MVC web application.Login information can be stored in databases when creating a new user account. Identity can be configured with SQL Server database to store user details such as emailid,username and password.

downlod source code

Step 1.

Creating .NET 5 Core MVC web application

  1. Open your visual studio 2017 or 2019
  2. Click on Create a New Project
  3. Select ASP.NET Core Web Application and Next
  4. Provide a Project name and confirm or change the Location. Select Create
  5. Select the latest version of ASP.NET Core in the drop-down (.NET Core 5.0)and then select Web Application
  6. Under Authentication, select Change and set the authentication to Individual User Accounts. Select OK
  7. In the Create a new ASP.NET Core Web Application window, select Create


Setup 2.

After created new project,open your appsettings.json and past this code like as given below

{
  "ConnectionStrings": {
    "windowsAuthentication": true,
    "DefaultConnection": "Data Source=<database-server-name>;Database=<database-name>; uid=<sql-userid>;pwd=<sql-password>;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Setup 3.

Now we have to add new DbContext.cs class in our application,for that we have to add multiple entity class in the under DbContext.cs.

Before doing something under the DbContext.cs class,three namespace are required we are install before doing something int the Dbcntext class.These namespace are given below.

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

After install package these namespace past this code in DbContext.cs cass like as given below.

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace LoginRegister
{
    public class DataContext : IdentityDbContext<IdentityUser, IdentityRole, string, IdentityUserClaim<string>, IdentityUserRole<string>,      IdentityUserLogin<string>, IdentityRoleClaim<string>, IdentityUserToken<string>>     {
        public DataContext(DbContextOptions<DataContext> options)
           : base(options)
        {
        }
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            builder.Entity<IdentityUser>();
        }
    }
}


Setp 4.

Install package from nutget because this package is required for database migration in .net core.

for more details click here

Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.SqlServer

Call connectionstring  from  our appsettings.json and  add CookiePolicyOptions,IdentityUserand DbContext.cs in our Startup.cs class like as given below.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LoginRegister
{
    public class Startup
    {
        public Startup(IConfiguration configuration, IWebHostEnvironment env)
        {
            Configuration = configuration;
            environment = env;
            var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
            Configuration = builder.Build();
        }
        public IConfiguration Configuration { get; }
        public IWebHostEnvironment environment;
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddDbContext<DataContext>(
             options => options.UseSqlServer("name=ConnectionStrings:DefaultConnection"));
            //services.AddIdentity<ApplicationUser,Role>().AddEntityFrameworkStores<DbContext>();
            services.AddIdentity<IdentityUser, IdentityRole>()
               .AddEntityFrameworkStores<DataContext>()
               .AddDefaultTokenProviders();
                 services.Configure<CookiePolicyOptions>(options =>
                 {
                     // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                     options.CheckConsentNeeded = context => true;
                     options.MinimumSameSitePolicy = SameSiteMode.None;
                 });
            services.AddSession(options =>
            {
                options.Cookie.SameSite = SameSiteMode.None;
                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
                options.Cookie.IsEssential = true;
            });
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }             else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.                 app.UseHsts();
            }
            app.UseStaticFiles();
            app.UseRouting();
            app.UseCors();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Now I have to perform migration operation to insert these newly created properties inside the SQL Server database.

or that go to tools, then click on Nuget Package Manager. Click on Package Manager Console.

To create Migration, we can execute Add-Migration command.

migration examle  in .net core


to update the database, execute command Update-Database.

After execute command update-database you can see the migrated class under Migrations folder like as given below.



Step 5.

Let’s begin with the RegistrationModel.cs class under the Models folder.

using System.ComponentModel.DataAnnotations;
namespace LoginRegister.Models
{
    public class RegisterViewModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        [Required(ErrorMessage = "Email is required")]
        [EmailAddress]
        public string Email { get; set; }
        [Required(ErrorMessage = "Password is required")]
        [DataType(DataType.Password)]
        public string Password { get; set; }
        [DataType(DataType.Password)]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }
}

in this RegisterViewModel.cs, we have a couple of properties the user populates in the registration form. As you can see the Email and Password properties are required and the ConfirmPassword property must match the Password property.

Also create LoginViewModel.cs class under the Models folder for login like as given below.

namespace LoginRegister.Models
{
    public class LoginViewModel
    {
        public string Email { get; set; }
        public string Password { get; set;}
    }
}

Now Create AccountController under the Controller folder and past this code like as given below.

using LoginRegister.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Threading.Tasks;
namespace LoginRegister.Controllers
{
    public class AccountController : Controller
    {
        private readonly UserManager<IdentityUser> _userManager;
        private readonly SignInManager<IdentityUser> _signInManager;
        public AccountController(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
        }
        public IActionResult Register()
        {
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)             {
                var user = new IdentityUser
                {
                    UserName = model.Email,                     Email = model.Email
                };
                var result = await _userManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    //add role here
                    await _userManager.AddToRoleAsync(user, "Admin");
                    return RedirectToAction("ActionName", "ControllerName");
                }
            }
            ModelState.AddModelError("", "Invalid Register.");
            return View(model);
        }
        public IActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, isPersistent: false, lockoutOnFailure: false);                 if (result.Succeeded)
                {
                    var user = await _userManager.FindByNameAsync(model.Email);
                    //user role list here
                    var roles = await _userManager.GetRolesAsync(user);
                    //get default role here
                    string role = roles.FirstOrDefault();
                    if (role.Equals("Admin"))
                    {
                        return RedirectToAction("AdminActionName", "AdminControllerName");
                    }
                    else if (role.Equals("User"))
                    {
                        return RedirectToAction("UserActionName", "UserControllerName");
                    }
                    else
                    {
                        //do somthing here.put in your logic
                    }
                }
            }
            ModelState.AddModelError("", "Invalid ID or Password");
            return View(model);
        }
    }
}


Now let's create Register page like as given below.

@model LoginRegister.Models.RegisterViewModel
<h1>Register</h1>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Register" asp-controller="Account">
            <div asp-validation-summary="All" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Email" class="control-label"></label>
                <input asp-for="Email" class="form-control" placeholder="Email"/>
                <span asp-validation-for="Email" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Password" class="control-label"></label>
                <input asp-for="Password" class="form-control" placeholder="Password" />
                <span asp-validation-for="Password" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ConfirmPassword" class="control-label"></label>
                <input asp-for="ConfirmPassword" class="form-control" placeholder="Confirm Password"/>
                <span asp-validation-for="ConfirmPassword" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Register" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

and at the last create login view page like as given below

@model LoginRegister.Models.LoginViewModel
<h1>Login</h1>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Login" asp-controller="Account">
            <div asp-validation-summary="All" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Email" class="control-label"></label>
                <input asp-for="Email" class="form-control" placeholder="Email" />
                <span asp-validation-for="Email" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Password" class="control-label"></label>
                <input asp-for="Password" class="form-control" placeholder="Password" />
                <span asp-validation-for="Password" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Login" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

When you create register and login page from account controller you can see these page like as given below.



In this article, I have discussed to how to create Registration and Login functionalities in .NET 5 Core  using Identity. I have added register and login razor view pages to register a new user and store user details using identity inside SQL Server database.I have create database using migration.



Mahira  khanna

Mahira khanna

I have the skills you need for you company blog, website, or other content materials

Comments



Report Response