Updated April 1, 2023
ASP.NET Core JWT Authentication
ASP.NET Core JWT Authentication is an open standard in which the data passes between the client and the server which allows transmitting the data between the server and consumers in a protected manner. Authentication is that validating the user with their credential details.
ASP.NET Core JWT Authentication Overviews
The ASP.NET Core JWT Authentication is a standard method for securing the APIs; it is expert in verifying the data transmitted over wired between APIs and clients which consume the APIs, we can safely pass the claims between the communicating parties as well. In Web Development, the JWT (JSON Web Token) is the most popular one. JSON Web Token (JWT) is the Open-Standard that enables to transmission of the data between the parties as a JSON object in protected and compressed mode. The transmission of data using JWT between parties are digitally signed which is easy to confirm and trustworthy.
JSON Web Token (which is called JWT) is an open standard in which the data passes between the client and the server which allows transmitting the data forth and back between the server and consumers in a protected manner. The token-based authentication process is nothing but the client sent a request to a server with the details of the credential. Once the server validates the credential then creates the access token which sends back to client, the process repeats until it’s expired.
Typical ASP.NET Core JWT Authentication Work
Developers are opinionated, web and mobile native apps are different, and the business scenarios are distinct, so we see a variety of approaches of using JWT. But the most common JWT flow works as follows:
ASP.NET Core JWT Authentication works in various ways like web, mobile apps, in business scenarios there will be different approaches, let’s see the followings
- Initially, user sends the credentials to logging in the website
- Then the Website back-end side validation done with those credentials then declares the appropriate claims and finally generates the JWT and returns to user.
- The user receives the JWT and holds it until it expires and then it sends the JWT to website consequent request.
- The website authenticates the JWT and makes a decision if the resources are available and then processes the request consequently.
The above flow of data shows that the security of JWT so that people recommend sending in JWT over HTTP’S and the access tokens of JWT must be short-term period and its not contains a sensitive data.
The JSON Web Token is an Open-Standard (RFC-7519) which defines the secure, compressed and independent safest way of transmission of information between sender and receiver by URL, HTTP Header and by a POST parameter. It is noticed which the information transmitted safely between two parties is represented in JSON format and is signed by cryptographically to confirm its accuracy. The JSON Web Token usually implementing authentication and authorization in web applications. Because JWT is a standard one the entire JWT’s are tokens, we can work with JSON Web Tokens in Java, Ruby, JavaScript, .NET, Python, Go, Node.js, and so on.
JSON Web Token symbolized that the combination of three base64url elements with concatenated period (‘.’) comprises and characters by three sections as follows,
- Header
- Payload
- Signature
Header Section
The header section makes available metadata about the type of data and for transferring the data that algorithm is to be encrypted. The header JWT consists of three sections they are metadata for a token, the encryption algorithm, and the type of signature and it consists of two properties they are “alg” and “typ”. The cryptography algorithm is used like HS256 to specify the data latter is used like JWT in this case.
{
"typ":"JWT",
"alg":"HS256"
}
Payload
The Payload Section represents the exact information in JSON format to be transmitted over the wire. Let’s see the coded payload given below,
{
"sub":"2333418709",
"name":"Smith",
"admin":true,
"jti":"cdafg345-209f-5ft8-8yg1-rt693dgs3469",
"iat":3434344343,
"exp":2354545454
"jti":"cdafg345-209f-5ft8-8yg1-rt693dgs3469",
"iat":4343434343,
"exp":434343434
}
The payload usually contains claims identity information of a user, permission allowed, and so on. To use the claims for the transmission of further information it is called the JWT claims and they are of two types they are Reserved and Custom. Let’s see the following reserved claims,
- iss: it denotes the issuer of token
- sub: it denotes the subject of token
- aud: it denotes the audience of token
- exp: it denotes the token expiration
- nbf: it denotes to mention the time before the token is not processed.
- iat: it denotes the time of issue token
- jti: it denotes the unique identifier of token
Custom claims also be used which can be added to tokens for the use of the rule.
Signature
The Signature section remains JSON Web Signature (JWS) pattern and is used to confirm the integrity of transferred data over the wire. It consists of the hash of header, secret, payload and which is used to make sure that message was not altered when it is being transmitted. The signed token is built by holding on to the JSON Web Signature (JWS) specification. The encoded JWT header, as well as the encoded JWT payload, is joined and it is signed with the use of an encryption algorithm like HMAC SHA 256.
Creating the Model Classes – ASP.NET Core JWT Authentication
The creation of model requires two entities which used in the application the classes are UserDetailsDTO and UserDetailsModel
public class UserDetailsModel
{
[Required]
public string UserName { get; set; }
[Required]
public string UserPassword { get; set; }
}
And then create the next model class of UserDetailsDTO as follows,
public class UserDetailsDTO
{
public string UserName { get; set; }
public string UserPassword { get; set; }
public string UserRole { get; set; }
}
The UserDetailsDTO denotes the object of user data transfer and which consist of three string properties they are UserName, UserPassword, UserRole.
Create ASP.NET Core JWT Authentication
In this let’s see how to implement the JWT authentication in ASP.NET Core application. Let see the following interfaces and classes,
- ITokenService: The ITokenServices is the interface that consists of the declaration of two methods they are IsTokenValid and
- BuildToken. The former is used to create the token and later is used to check whether the token is valid.
- TokenService: This TokenService class extends the ITokenService interface and which implements their methods.
- IUserRepository: The IUserRepository interface contains the declaration of GetUser method and which is used to get the
- UserDetailsDTO instance based on the username from the class UserModel Class.
- UserRepositroy: The UserRepository class extends the IUserRepository interface and that implements the method of GetUser.
It contains the sample data which used by the application as of the class UserDetailsDTO.
Example
Let’s see one example, consider testing with the developed Web API testing in the Fiddler, initially request in the “API/Login” method to generate the token. To pass the following JSON in the request body,
As a response, we will get the JSON like the following,
{
"token" : "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJKaWduZXNoIFRyaXZlZGkiLCJlbWFpbCI6InRlc3QuYnRlc3RAZ21haWwuY29tIiwiRGF0ZU9mSm9pbmciOiIwMDAxLTAxLTAxIiwianRpIjoiYzJkNTZjNzQtZTc3Yy00ZmUxLTgyYzAtMzlhYjhmNzFmYzUzIiwiZXhwIjoxNTMyMzU2NjY5LCJpc3MiOiJUZXN0LmNvbSIsImF1ZCI6IlRlc3QuY29tIn0.8hwQ3H9V8mdNYrFZSjbCpWSyR1CNyDYHcGf6GqqCGnY"
}
Conclusion
In this article have explained the JWT, which is an open-standard web development platform that enables to transmit the data between parties in JSON Object in a secure way. Hope the article helps you to understand.
Recommended Articles
This is a guide to ASP.NET Core JWT Authentication. Here we discuss the Introduction, overviews, Typical ASP.NET Core JWT Authentication Work, and examples with code implementation. You may also have a look at the following articles to learn more –