Updated March 29, 2023
Introduction to ASP.NET Core Authentication
ASP.NET Core Authentication is the process of establishing the user’s individuality. The ASP.NET Core Authentication is managed by the service IAuthenticationService which is used by the authentication middleware. The services make use of the registered authentication handlers to finish it the authentication-linked actions. One of the examples for authentication connected action which includes the Authenticating of a user.
Overview ASP.NET Core Authentication
The ASP.NET Core Authentication is the process of authenticating the user credentials, whereas the Authorization is the process of ensuring the rights for the user to make use of particular modules in the application. ASP.NET Core Authentication is the process of establishing the user’s identity. It is the process of actions which is to check the user’s credentials in the database. If the user provides their basic details or credentials, we have to set them, or our application requires the Login-Page with the set fields to interact with. The ASP.NET Core Authentication is managed by the service IAuthenticationService which is used by the authentication middleware.
Let’s see how to execute the user authentication with ASP.NET Core Identity. Our essential thing in this authentication process is to create the user Login-Page and set actions required to validate the credentials. Thus, authentication is the process of establishing the user’s individuality. The ASP.NET Core Authentication is managed by the service IAuthenticationService which is used by the authentication middleware.
There is an example for authenticating the connected action, which includes:
- Authenticate a user.
- Take actions if there is an un-authenticated user trying to access the resources without permission.
The secured configuration options and authentication handlers are known as the Schemes. The Authentication schemes are precised by securing the authentication services in startup.configureservices, once making a call with scheme-specific extension method, then make a call to the services called services.AddAuthentication (like AddJwtBearer or AddCookie). Those extension methods make use of the AuthenticationBuilder.AddScheme for the registration in schemes with the proper setting.
ASP.NET Core Authentication Services
Example for the registered authentication handlers and the services for the JWTbearer authentication schemes and cookies.
Services . AddAuthentication (JwtBearerDefaults AuthenticationScheme)
AddJwtBearer (JwrBearerDefaults.AuthenticationScheme,
option=> Configuration.Bind("JwtSettings", options))
AddCookie ( CookieAuthenticationDefaults.AuthenticationScheme,
Options => Configuration.Bind ("CookieSettings",options));
There are various types of authentication as follows:
- None: No authentication.
- Windows: Windows authentication.
- Individual: There is an individual authentication.
- IndividualB2C: Azure AD B2C individual authentication.
- SingleOrg: There is a single-tenant of organizational authentication.
- MultiOrg: There are multiple tenants of organizational authentication.
Preparing Authentication Environment
- Initially, we need to disable the unauthorized users to the right to use the Employees Action method.
We need to add the attribute like [Authorize] on the top of the action method.
[Authorize]
public async Task<IActionResult> EmployeeDetial()
{
var employees_obj = await _context.EmployeeDetial.ToListAsync();
return View(employees_obj);
}
- In addition, we need to add the authentication Middleware to the ASP.NET Core in the configuration method above the app.UseAuthorization() expression.
- When executing the application, click on the EmployeeDetails Link, we will get the Not Found 404 response.
- We are getting the Not Found page because, by default, the ASP.NET Core induvality attempts to redirect the un-authorized user to the Action method; it does not exist.
- In addition, we can able to see the ReturnUrl string query, which is used to provide the path needed for action before the user is redirected to the Login page.
- To fix this problem (404 Error) we need to do the two things in major.
- Firstly to create the UserLoginModel class in the folder of Model.
First, let’s create a UserLoginModel class in the Models folder:
public class UserLoginModel
{
[Required]
[EmailAddress]
public string User_Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string User_Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
Once including the user model, then add the two actions to the Account Controller.
[HttpGet]
public IActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(UserLoginModel user_Model)
{
return View();
}
We no need to navigate the Login Page by right to use secured action; we can set the individual link for making use of it. Let’s alter the _Login view.
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link text-dark" asp-controller="Account"
asp-action="Login">Login Module</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-controller="Account"
asp-action="Register"> Click here to Register! </a>
</li>
</ul>
At last, to create the Login View, by building the textbox, labels, and so on. Once creating the user interface for the login view, just code the page for submit button. Finally, implement the ASP.NET Core Authentication for user identity. Once clicking the submit button, it performs the POST action for login.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(UserLoginModel userModel)
{
if (!ModelState.IsValid)
{
return View(userModel);
}
var user = await _userManager.FindByEmailAsync(userModel.User_Email);
if (user != null &&
await _userManager.CheckPasswordAsync(user, userModel.User_Password))
{
var identity = new ClaimsIdentity(IdentityConstants.ApplicationScheme);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme,
new ClaimsPrincipal(identity));
return RedirectToAction(nameof(HomeController.Index), "Home");
}
else
{
ModelState.AddModelError("", "Wrong! Please Check Your Credentials");
return View();
}
}
In this above code, it describes that the user is a valid user. Initially, we check if the model is invalid; if so, then return the view with the model. Afterward, we using the FindByEmailAsync method in the UserManager, which returns the user by the Email. Once entering the user name or email-id, it first check whether the user exists and checks the passwords matches to the specific user it matches with the hashed password from the database, then we creating the ClaimsIdentity object with the claims (like ID and the UserName). Then, automatically, it sign-in the user with the SignInAsyn method by presenting with the schema attribute with claim principal. Finally, it will build the Identity.Application cookie in the browser. Once all process passes correctly, it redirects the user to their corresponding Index action.
If the user is not a valid user or the user does not exist in the database, it returns with the failed messages.
Conclusion
In this article, we have seen what the ASP.NET Core Authentication is about; it is the process of establishing the user’s identity. By using this, we can ensure the user identity in every application for securing usage.
Recommended Articles
We hope that this EDUCBA information on “ASP.NET Core Authentication” was beneficial to you. You can view EDUCBA’s recommended articles for more information.