<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>login registration asp net core &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/login-registration-asp-net-core/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>ASP.NET Hosting &#124; Reviews &#124; Tips &#38; Tutorial</description>
	<lastBuildDate>Fri, 22 Jul 2022 04:49:59 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://topreviewhostingasp.net/wp-content/uploads/2017/01/cropped-trhaico-32x32.png</url>
	<title>login registration asp net core &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Create Registration and Login in ASP.NET Core Apps Using Identity</title>
		<link>https://topreviewhostingasp.net/how-to-create-registration-and-login-in-asp-net-core-apps-using-identity/</link>
					<comments>https://topreviewhostingasp.net/how-to-create-registration-and-login-in-asp-net-core-apps-using-identity/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Fri, 22 Jul 2022 04:48:14 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[asp net]]></category>
		<category><![CDATA[asp net core]]></category>
		<category><![CDATA[asp net core tips]]></category>
		<category><![CDATA[asp net core tutorial]]></category>
		<category><![CDATA[asp net tips]]></category>
		<category><![CDATA[asp net tutorial]]></category>
		<category><![CDATA[login registration asp net core]]></category>
		<category><![CDATA[using identity asp net core]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3082</guid>

					<description><![CDATA[ASP.NET Core Identity is an API that supports login functionality in ASP.NET Core MVC web application. Login information can be stored in identity when creating a new user account. Identity can be configured with SQL Server database to store user details such as username, password and email id. So in this article I will explain [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>ASP.NET Core Identity is an API that supports login functionality in ASP.NET Core MVC web application. Login information can be stored in identity when creating a new user account. Identity can be configured with SQL Server database to store user details such as username, password and email id. So in this article I will explain how to use identity to register, login and logout of a user account.</p>



<h2 class="wp-block-heading">Creating ASP.NET Core MVC web application</h2>



<p> Create ASP.NET Core MVC web application as follows</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img fetchpriority="high" decoding="async" width="498" height="378" class="wp-image-3083 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/07/image_1.jpg" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/07/image_1.jpg 498w, https://topreviewhostingasp.net/wp-content/uploads/2022/07/image_1-300x228.jpg 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/07/image_1-50x38.jpg 50w" sizes="(max-width: 498px) 100vw, 498px" /></figure>
</div>



<p>Select ASP.NET Core Web Application from the template and provide the project name and location where this project can be saved.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" width="476" height="300" class="wp-image-3084 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/07/aspnetcore-1.jpg" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/07/aspnetcore-1.jpg 476w, https://topreviewhostingasp.net/wp-content/uploads/2022/07/aspnetcore-1-300x189.jpg 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/07/aspnetcore-1-50x32.jpg 50w" sizes="(max-width: 476px) 100vw, 476px" /></figure>
</div>



<p>Select MVC template along with ASP.NET Core latest version and click on create button for the application to be created. Now we have to add ASP.NET Core Identity in our application. To add identity right click on the project name, click on Add option and the click on New Scaffolded Item.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" width="470" height="266" class="wp-image-3085 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/07/aspnetcore-2.jpg" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/07/aspnetcore-2.jpg 470w, https://topreviewhostingasp.net/wp-content/uploads/2022/07/aspnetcore-2-300x170.jpg 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/07/aspnetcore-2-50x28.jpg 50w" sizes="(max-width: 470px) 100vw, 470px" /></figure>
</div>



<p>Select the Identity option and click on Add button. Now we can select login and register razor pages from ASP.NET Core Identity.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="394" height="261" class="wp-image-3086 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/07/aspnetcore-3.jpg" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/07/aspnetcore-3.jpg 394w, https://topreviewhostingasp.net/wp-content/uploads/2022/07/aspnetcore-3-300x199.jpg 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/07/aspnetcore-3-50x33.jpg 50w" sizes="(max-width: 394px) 100vw, 394px" /></figure>
</div>



<p>Select the layout page for the razor pages, provide the data context class for database related operations and User class to customize the given registration razor page. Now click on Add button.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="222" height="354" class="wp-image-3087 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/07/loginauth.jpg" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/07/loginauth.jpg 222w, https://topreviewhostingasp.net/wp-content/uploads/2022/07/loginauth-188x300.jpg 188w, https://topreviewhostingasp.net/wp-content/uploads/2022/07/loginauth-31x50.jpg 31w" sizes="(max-width: 222px) 100vw, 222px" /></figure>
</div>



<p>As we can see identity is added inside Areas folder. Inside Area folder both data as well as razor pages have been added. Now we have to add user authentication into this application, for that we have to modify startup.cs class. We have to add support for razor pages inside the application.</p>



<pre class="wp-block-code"><code>public void ConfigureServices(IServiceCollection services)  
        {  
            services.AddControllersWithViews();  
            services.AddRazorPages();  
        }  </code></pre>



<p>Inside ConfigureServices method, we have to call the function AddRazorPages. To include identity into this application we have to call UseAuthentication function inside configure method.</p>



<pre class="wp-block-code"><code>app.UseAuthentication();  
</code></pre>



<p>Now we need to add url’s for login and register pages, for that we have to call a function called MapRazorPages inside UseEndpoints.</p>



<pre class="wp-block-code"><code>app.UseEndpoints(endpoints =&gt;  
            {  
                endpoints.MapControllerRoute(  
                    name: "default",  
                    pattern: "{controller=Home}/{action=Index}/{id?}");  
                endpoints.MapRazorPages();  
            }); </code></pre>



<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://www.asphostportal.com" target="_blank" rel="noopener"><img loading="lazy" decoding="async" width="300" height="271" class="wp-image-2584 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01-50x45.png 50w" sizes="(max-width: 300px) 100vw, 300px" /></a></figure>
</div>



<p>Now we need to create database for the application.</p>



<pre class="wp-block-code"><code>using System.Threading.Tasks;  
using Microsoft.AspNetCore.Identity;  
  
namespace LoginAuth.Areas.Identity.Data  
{  
    // Add profile data for application users by adding properties to the ApplicationUser class  
    public class ApplicationUser : IdentityUser  
    {  
        [PersonalData]  
        [Column(TypeName="nvarchar(100)")]  
        public string FirstName { get; set; }  
  
        [PersonalData]  
        [Column(TypeName = "nvarchar(100)")]  
        public string LirstName { get; set; }  
  
    }  
}  </code></pre>



<p>Here we are adding properties for first name and last name. Inside user table it will be  personal data, that is why we need to add attribute personal data. We can also define the data types of each property with the help of attribute column. </p>



<p>Now we have to perform migration operation to insert these newly created properties inside the SQL Server database. </p>



<p>For that go to tools, then click on Nuget Package Manager. Click on Package Manager Console. </p>



<p>To create Migration, we can execute Add-Migration command.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="858" height="194" class="wp-image-3088 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/07/migration-command.jpg" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/07/migration-command.jpg 858w, https://topreviewhostingasp.net/wp-content/uploads/2022/07/migration-command-300x68.jpg 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/07/migration-command-768x174.jpg 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/07/migration-command-50x11.jpg 50w" sizes="(max-width: 858px) 100vw, 858px" /></figure>
</div>



<p>To update the database, execute command Update-Database. </p>



<p>We can see the newly created database LoginAuthDB in SQL Server below</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="241" height="330" class="wp-image-3089 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/07/sql.jpg" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/07/sql.jpg 241w, https://topreviewhostingasp.net/wp-content/uploads/2022/07/sql-219x300.jpg 219w, https://topreviewhostingasp.net/wp-content/uploads/2022/07/sql-37x50.jpg 37w" sizes="(max-width: 241px) 100vw, 241px" /></figure>
</div>



<p>In order to display form controls for first name and last name inside registration form, we have to update the input model inside register.cshtml.cs file by adding corresponding properties inside the input model.</p>



<pre class="wp-block-code"><code>public class InputModel  
        {  
            [Required]  
            [DataType(DataType.Text)]  
            [Display(Name = "First Name")]  
            public string FirstName { get; set; }  
  
            [Required]  
            [DataType(DataType.Text)]  
            [Display(Name = "Last Name")]  
            public string LirstName { get; set; }  
  
            [Required]  
            [EmailAddress]  
            [Display(Name = "Email")]  
            public string Email { get; set; }  
  
            [Required]  
            [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]  
            [DataType(DataType.Password)]  
            [Display(Name = "Password")]  
            public string Password { get; set; }  
  
            [DataType(DataType.Password)]  
            [Display(Name = "Confirm password")]  
            [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]  
            public string ConfirmPassword { get; set; }  
        }  </code></pre>



<p>We also need to add the same inside the OnPostAsync function for saving the record.</p>



<pre class="wp-block-code"><code>public async Task&lt;IActionResult&gt; OnPostAsync(string returnUrl = null)  
        {  
            returnUrl = returnUrl ?? Url.Content("~/");  
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();  
            if (ModelState.IsValid)  
            {  
                var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email,FirstName = Input.FirstName,LirstName = Input.LirstName };  
                var result = await _userManager.CreateAsync(user, Input.Password);  
                if (result.Succeeded)  
                {  
                    _logger.LogInformation("User created a new account with password.");  
  
                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);  
                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));  
                    var callbackUrl = Url.Page(  
                        "/Account/ConfirmEmail",  
                        pageHandler: null,  
                        values: new { area = "Identity", userId = user.Id, code = code },  
                        protocol: Request.Scheme);  
  
                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",  
                        $"Please confirm your account by &lt;a href='{HtmlEncoder.Default.Encode(callbackUrl)}'&gt;clicking here&lt;/a&gt;.");  
  
                    if (_userManager.Options.SignIn.RequireConfirmedAccount)  
                    {  
                        return RedirectToPage("RegisterConfirmation", new { email = Input.Email });  
                    }  
                    else  
                    {  
                        await _signInManager.SignInAsync(user, isPersistent: false);  
                        return LocalRedirect(returnUrl);  
                    }  
                }  
                foreach (var error in result.Errors)  
                {  
                    ModelState.AddModelError(string.Empty, error.Description);  
                }  
            }  
  
            // If we got this far, something failed, redisplay form  
            return Page();  
        } </code></pre>



<p>Here we are passing both first name and last name. </p>



<p>Now we need to update the registration form inside Register.cshtml</p>



<pre class="wp-block-code"><code>@page  
@model RegisterModel  
@{  
    ViewData["Title"] = "Register";  
}  
  
&lt;h1&gt;@ViewData["Title"]&lt;/h1&gt;  
  
&lt;div class="row"&gt;  
    &lt;div class="col-md-4"&gt;  
        &lt;form asp-route-returnUrl="@Model.ReturnUrl" method="post"&gt;  
            &lt;h4&gt;Create a new account.&lt;/h4&gt;  
            &lt;hr /&gt;  
            &lt;div asp-validation-summary="All" class="text-danger"&gt;&lt;/div&gt;  
            &lt;div class="form-group"&gt;  
                &lt;label asp-for="Input.FirstName"&gt;&lt;/label&gt;  
                &lt;input asp-for="Input.FirstName" class="form-control" /&gt;  
                &lt;span asp-validation-for="Input.FirstName" class="text-danger"&gt;&lt;/span&gt;  
            &lt;/div&gt;  
            &lt;div class="form-group"&gt;  
                &lt;label asp-for="Input.LirstName"&gt;&lt;/label&gt;  
                &lt;input asp-for="Input.LirstName" class="form-control" /&gt;  
                &lt;span asp-validation-for="Input.LirstName" class="text-danger"&gt;&lt;/span&gt;  
            &lt;/div&gt;  
            &lt;div class="form-group"&gt;  
                &lt;label asp-for="Input.Email"&gt;&lt;/label&gt;  
                &lt;input asp-for="Input.Email" class="form-control" /&gt;  
                &lt;span asp-validation-for="Input.Email" class="text-danger"&gt;&lt;/span&gt;  
            &lt;/div&gt;  
            &lt;div class="form-group"&gt;  
                &lt;label asp-for="Input.Password"&gt;&lt;/label&gt;  
                &lt;input asp-for="Input.Password" class="form-control" /&gt;  
                &lt;span asp-validation-for="Input.Password" class="text-danger"&gt;&lt;/span&gt;  
            &lt;/div&gt;  
            &lt;div class="form-group"&gt;  
                &lt;label asp-for="Input.ConfirmPassword"&gt;&lt;/label&gt;  
                &lt;input asp-for="Input.ConfirmPassword" class="form-control" /&gt;  
                &lt;span asp-validation-for="Input.ConfirmPassword" class="text-danger"&gt;&lt;/span&gt;  
            &lt;/div&gt;  
            &lt;button type="submit" class="btn btn-primary"&gt;Register&lt;/button&gt;  
        &lt;/form&gt;  
    &lt;/div&gt;  
      
&lt;/div&gt;  
  
@section Scripts {  
    &lt;partial name="_ValidationScriptsPartial" /&gt;  
}  </code></pre>



<p>A new user can now register in our application. After filling the login information and clicking on login button, once the user is logged in to the application corresponding email id link and logout button can be displayed by including _LoginPartial.cshtml file inside _Logout.cshtml file as follows</p>



<pre class="wp-block-code"><code>&lt;!DOCTYPE html&gt;  
&lt;html lang="en"&gt;  
&lt;head&gt;  
    &lt;meta charset="utf-8" /&gt;  
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt;  
    &lt;title&gt;@ViewData["Title"] - LoginAuth&lt;/title&gt;  
    &lt;link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" /&gt;  
    &lt;link rel="stylesheet" href="~/css/site.css" /&gt;  
&lt;/head&gt;  
&lt;body&gt;  
    &lt;header&gt;  
        &lt;nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3"&gt;  
            &lt;div class="container"&gt;  
                &lt;a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index"&gt;LoginAuth&lt;/a&gt;  
                &lt;button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"  
                        aria-expanded="false" aria-label="Toggle navigation"&gt;  
                    &lt;span class="navbar-toggler-icon"&gt;&lt;/span&gt;  
                &lt;/button&gt;  
                &lt;div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse"&gt;  
                    &lt;partial name="_LoginPartial.cshtml" /&gt;  
                &lt;/div&gt;  
            &lt;/div&gt;  
        &lt;/nav&gt;  
    &lt;/header&gt;  
    &lt;div class="container"&gt;  
        &lt;main role="main" class="pb-3"&gt;  
            @RenderBody()  
        &lt;/main&gt;  
    &lt;/div&gt;  
  
    &lt;footer class="border-top footer text-muted"&gt;  
        &lt;div class="container"&gt;  
            © 2020 - LoginAuth - &lt;a asp-area="" asp-controller="Home" asp-action="Privacy"&gt;Privacy&lt;/a&gt;  
        &lt;/div&gt;  
    &lt;/footer&gt;  
    &lt;script src="~/lib/jquery/dist/jquery.min.js"&gt;&lt;/script&gt;  
    &lt;script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"&gt;&lt;/script&gt;  
    &lt;script src="~/js/site.js" asp-append-version="true"&gt;&lt;/script&gt;  
    @RenderSection("Scripts", required: false)  
&lt;/body&gt;  
&lt;/html&gt; </code></pre>



<p>We can also provide authentication feature to the application so that only authenticated users will be able to login inside the application. For that we have add Authorize attribute inside Home Controller as follows.</p>



<pre class="wp-block-code"><code>using System;  
using System.Collections.Generic;  
using System.Diagnostics;  
using System.Linq;  
using System.Threading.Tasks;  
using Microsoft.AspNetCore.Mvc;  
using Microsoft.Extensions.Logging;  
using LoginAuth.Models;  
using Microsoft.AspNetCore.Authorization;  
  
namespace LoginAuth.Controllers  
{  
    [Authorize]  
    public class HomeController : Controller  
    {  
        private readonly ILogger&lt;HomeController&gt; _logger;  
  
        public HomeController(ILogger&lt;HomeController&gt; logger)  
        {  
            _logger = logger;  
        }  
  
        public IActionResult Index()  
        {  
            return View();  
        }  
  
        public IActionResult Privacy()  
        {  
            return View();  
        }  
  
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]  
        public IActionResult Error()  
        {  
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });  
        }  
    }  
}  </code></pre>



<p><strong>Output</strong> </p>



<p>If we run the application, we will be redirected to login page because user is not authenticated.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="406" height="452" class="wp-image-3090 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/07/loginauth_2.jpg" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/07/loginauth_2.jpg 406w, https://topreviewhostingasp.net/wp-content/uploads/2022/07/loginauth_2-269x300.jpg 269w, https://topreviewhostingasp.net/wp-content/uploads/2022/07/loginauth_2-45x50.jpg 45w" sizes="(max-width: 406px) 100vw, 406px" /></figure>
</div>



<p>Registered user details are stored inside SQL Server database as follows</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="792" height="69" class="wp-image-3091 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/07/sql-2.jpg" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/07/sql-2.jpg 792w, https://topreviewhostingasp.net/wp-content/uploads/2022/07/sql-2-300x26.jpg 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/07/sql-2-768x67.jpg 768w, https://topreviewhostingasp.net/wp-content/uploads/2022/07/sql-2-50x4.jpg 50w" sizes="(max-width: 792px) 100vw, 792px" /></figure>
</div>



<p>Once a user is logged in, the user will be redirected to the home page.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="575" height="299" class="wp-image-3092 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2022/07/loginauth3.jpg" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2022/07/loginauth3.jpg 575w, https://topreviewhostingasp.net/wp-content/uploads/2022/07/loginauth3-300x156.jpg 300w, https://topreviewhostingasp.net/wp-content/uploads/2022/07/loginauth3-50x26.jpg 50w" sizes="(max-width: 575px) 100vw, 575px" /></figure>
</div>



<h2 class="wp-block-heading">Summary</h2>



<p> In this article, we have discussed to how to create Registration and login functionalities in ASP.NET Core web application using Identity. We have added register and login razor pages to register a new user and store user details using identity inside SQL Server database. We also modified the existing registration page by adding first name and last name properties inside the register. cshtml file. We also provided authentication feature to the application so that only authenticated user will be able to login inside the application.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-create-registration-and-login-in-asp-net-core-apps-using-identity/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
