Understanding Authentication and Authorization in ASP .NET Core with Example
.NET Core

Understanding Authentication and Authorization in ASP .NET Core with Example

Mishel Shaji
Mishel Shaji

In this post, we'll learn about authentication and authorization in ASP .NET Core.

Authentication [Who are you?]

Authentication is a process of verifying the identity of a person or any device. A simple example of authentication is entering a username and password when you log in to any website. These credentials are verified from the database or any other alternative, if it exists then the user is a valid candidate for the next Process-Authorization.

Username/password is a common way of authenticating the user’s identity.

Authorization [Can you do that?]

Authorization is the process of determining whether a user has access to a resource after authentication based on their identity and check the user has sufficient rights to access the requested resources. Resources can be ASP.NET web page, media files, Compressed file, etc.

Authorization is also known as “Permission Control” and it will come after authentication.

The Core Difference with  Real-life Example:

When you’re at the airport, there are two things you must have – passport and boarding pass. When you go through security checking, you provide your passport and boarding pass. These are used as your identification. Your passport is one type of authentication. It specifies that you are a particular person, and you have provided proof that this is true.

When you check in to your gate, however, a passport isn’t required. To actually board the plane, you need to provide a boarding pass. This boarding pass works as a token of trust between the airline and you – it confirms your right to be on a flight. In that way, a boarding pass is one type of authorization, showing that you are allowed to the plane.

Types of Authentication in Asp.Net:

1. Form Authentication

Form authentication depends on cookies, the authentication setting and permission settings are stored in cookies. we can also use cookie-less form authentication we can use query string for passing user details.

Form authentication steps are as follow:

1. When a user requests a page for the application, ASP.NET checks the session cookie. If the cookie exists in the browser and it is valid then ASP.NET assumes the user is authenticated and processes the next request.

2. If session cookies do not exist or not valid then it redirects to the login form.

3. User will enter username and password and if they are valid then he will get authenticated and authorized.

2. Passport Authentication

Passport authentication is an authentication facility provided by Microsoft. The .NET Passport single sign-in service. When we use passport authentication then user authentication in your application is managed by Microsoft’s passport service. Encrypted cookies are used for Passport Authentication.

3. Windows Authentication

We use windows authentication when we are creating a web application for limited users who have a Windows account. This authentication method uses the local user’s Windows account ‘credentials’ to validate the user. Dot Net web application is hosted on IIS (Internet Information Server), so the requests would go to IIS, and IIS provides the authentication process in a Windows-based authentication model.

IIS handles the entire responsibility of authentication. It first takes the user’s credentials from the login. If this process is denied, then IIS displays an alert dialog box for the user so the user can enter or re-enter his login information.

4. Custom Authentication

  1. Multipass

Multipass authentication is a single sign-on authentication. Single Sign-On is an authentication process that allows users to share his authentication details and manage multiple sites through it. A multipass is a combination of the hash of keys and values, provided as an AES encrypted JSON hash.

  1. JWT (JSON Web token)

JWTs represent a JSON object and that is encoded in a JWS and/or JWE structure. This JSON object is called “JWT Claims Set”. The JSON object contains name/value pairs (or members), where the names are strings and the values are arbitrary JSON values. These members are the claims represented by the JWT. JWT use token-based authentication.

Authorization in Asp.Net:

Role-Base Authorization

Roles are permission given to the user. Once the user is authenticated, then the resource the user can access is identified by his role.

Policy-Based Authorization

The policy-based Authorization contains three concepts: Policies, requirements, and handlers.

  1. Policy: Policy is composed of one or more requirements.
  2. Requirement: Requirement is a collection of data parameters used by policy to evaluate the user Identity.
  3. Handler: Handler is used for evaluating the properties of the requirements to determine if the user is authorized to access a specific resource.

Example of Authentication and Authorization Using Identity in Asp.net Core:

Form Authentication is implemented by Identity in Asp.net Core. Identity Provide many options like Windows authentication and third-party providers like Google, Microsoft, Facebook, and GitHub.

This authentication technique is based on the OWIN (Open Web Interface for .Net) Library. Let us have a glimpse over the significant components –

1. User: The basic authentication details such as user ID and password as well as profile information of a user make a User object. ASP.NET Identity comes with the IdentityUser class that contains basic authentication information.

2. Role: Role Object Represent User Role. The basic role is provided by the IdentityRole class of ASP.NET.

3. User Manager: ASP.NET Identity comes with the UserManager class that can be used for creating users, removing users, change passwords.

4. Role Manager: ASP.NET Identity comes with the RoleManager class that can be used for creating a role, checking role whether it exists or not.

5. Authentication Manager: Authenticating a user – signing in and signing out a user – is the responsibility of the Authentication Manager. ASP.NET Identity provides the IAuthenticationManager interface that represents an authentication manager

Implement Identity in Your project:

Go to Visual Studio and create a new Asp.net Core application and select web application with authentication set to an individual user account, that new project will include all identity framework set up for you.

Individual user account user authentication model

Now, Open the appsettings.json file and add the connection string in DefaultConnection.

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=.;Initial Catalog=<DB_NAME>;Integrated Security=true;"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

Now, open the Package Manager Console from the Tools menu and run the below commands one by one.

add-migration demoIdentity
update-database

Go to, SQL server and check related database has been created.

Identity tables

Build and Run Application.

Default authentication page of ASP .NET Core

Add Service to the ConfigureService Method in Startup.cIdentity provides default authentication using app.UseAuthentication(); in Configure method  to Authenticate  user. And [Authorize] attribute is used in Account Controller for authentication.

Add [Authorize] attribute to the method which you want to authorize.

Checking the user role

Roles-based Authorization makes it possible to make a particular Action or Controller accessible only to the specified roles.

[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
}

Policy based role check

We can register policy at the startup file.

services.AddAuthorization(options =>
{
    options.AddPolicy("RequireAdministratorRole",
             policy => policy.RequireRole("Administrator"));
});
[Authorize(Policy = "RequireAdministratorRole")]
public class UpdateUser : User
{
    public ActionResult OnPost()
    {
    }
}

Conclusion

In this article, we have learned about how authentication and authorization mechanisms work using the Asp.Net Core platform. Authentication and Authorization plays a strong role in any platform, hence it is recommended to understand as much as possible.

Author Bio: Ajay Patel – Technical Director, iFour Technolab Pvt Ltd.

Profile photo of Ajay Patel

A seasoned technocrat with years of experience building technical solutions for various industries using Microsoft technologies. Wish sharp understanding and technical acumen, have delivered hundreds of Web, Cloud, Desktop, and Mobile solutions and is heading the technical department at ASP.NET Core Software Company – iFour Technolab Pvt Ltd.

LinkedIn: https://www.linkedin.com/in/ajay-patel-8406167a