As we have seen in many of our previous articles, the world is moving towards API and microservice architecture. Now, Imagine an API that is part of the backend operations of an e-commerce website.
In an e-commerce website, individual accounts will be created for maintaining and tracking orders, payment details, and many other processes. To see the account information, the user has to login through the UI. So, now let us understand what happens in the background. From the e-commerce website, the user sends the username and password. The backend code validates the details and sends back a bearer token to the front end. It starts to communicate further to get the details about the user, send me this.
So, the user will be logged into the system at this point. Now, the user requests account details. The front-end application asks for the account details of the particular user to the backend API by sending the token. At this juncture, there has to be a logic in the backend code that validates whether the user is authenticated or not. Only then the system can send the secure information.
If that operation is open to everyone and anyone can see anyone’s details, then it becomes a security issue and a lot of mishaps can happen. To secure the controller and endpoints that contain the backend operations, .Net provides Authentication services along with .Net Core. Let’s see in detail about the authentication in this blog.
Table of contents
- What is Authentication?
- What is the Authentication scheme?
- Practical Implementation of Authentication in .Net Core,
What is Authentication?
Authentication is the process of validating whether the person or the entity who they claim to be is correct. It provides the control to validate the input credentials against the authentication server or database which is being used for storing the details.
It allows organizations to protect their application and enables only authenticated users to access the company’s resources. It includes accessing information of the user that is registered with the company, accessing the company’s network for performing operations, and also allowing employees of the company to work remotely by accessing the company’s data.
What is the Authentication Scheme?
The authentication scheme is the bundle that consists of an authentication handler and options to configure the specified handler. Schemes are used to choose the authentication mechanism, challenge and forbid the behavior of a handler. A default authentication scheme is used until one is explicitly specified.
An authentication scheme has an authenticate action which creates an AuthenticateResult. This in turn provides information on whether the user was successfully authenticated or not. On successful validation, it sends the user’s identity in the authentication ticket.
When an unauthenticated user tries to hit an endpoint, an authentication challenge is invoked by the Authorization using the specified authorization scheme. A forbidden action is called if a restricted piece of code is being accessed by the end-user.
Practical Implementation of Authentication in .Net Core
In this section, let’s see in detail how to implement an Authentication mechanism in .Net Core-based API.
To test the below code, a third-party software ‘Postman’ will be used.
Create a .Net Core-based web application project using the Microsoft visual studio IDE and provide the required path and name for the solution.
Choose the ASP.Net core web application template as API and ensure it is pointed to .Net Core and the version is .Net Core 3.1.
On creating the project, the code structure of the project will look similar to the below image. Where a default weather forecast controller would be included as a part of the project.
In this example, we are going to authenticate the JWT based bearer token. Let’s open the appsettings.json file that is present in the project and configure the required details for validating JWT. To validate a JWT, we need an Issuer, Audience, and a key to validate the issuer. The appsettings.json file by default comes with the logging settings. Along with that, we are going to add the settings for JWT.
The next step is to validate the created configuration against the request data. The code to validate the request header with configuration will be done in the startup file. There is a ConfigureServices method present in the startup method, it is where the changes for validation have to be made.
First, the required package — Microsoft.AspNetCore.Authentication.JwtBearer has to be installed. Then add the AuthenticationScheme of the JwtBearerDefaults.
Along with the above header reference, below header files need to be added.
using Microsoft.IdentityModel.Tokens and using System.Text;
Now, in the weatherforecast controller, create a method that generates a token to validate it against the code which has been implemented. The method creates the bearer token with the same issuer, audience, and key to validate the user.
Open the postman tool and call the endpoint https://localhost:44394/weatherforecast/token. Check whether you are able to see the bearer token in the response.
Now, let’s try to hit the default endpoint that comes with the API code and see how the response looks. Note — Do not add the authorize shorthand to the method.
Check whether you are able to see the response in the output section.
Let’s add the Authorize shorthand
Call the same endpoint from the postman again. Do you see the 401 unauthorized as the response in the response section?
Let’s make a success call by getting the bearer token and then make the call to the get method by passing the bearer token in the Authorization header of the get request.
Thus, this simple application explains how to validate a JWT and authorize the request.
Securing the features in an application is as important as implementing the features in the application. Authorization plays a key role in securing the endpoints and provides valuable features to the user along with security.
Originally published at https://www.partech.nl.