Updated April 3, 2023
Introduction to ASP.NET Core JWT
ASP.NET Core JWT (JSON Web Token) is the most accepted Web Development. It is an Open Standard that enables data transmission between parties as a JSON Object in a protected and compressed method. Furthermore, the transmission of data using JWT between the parties is digitally signed to be simply confirmed and confidential. Thus, the JSON Web Token is the paradigm for sharing safety information between parties.
What is ASP.NET Core JWT?
- The JSON Web Token is the token that the server can create, including the data payload. The JSON Web Token (JWT) payload encloses the things, including the Email/ UserID, so that the client sends you the JWT and ensures you that you issue it.
- JWT is mainly used to transmit data between the client and the server, allowing you to transmit a forth and back between the client and the server in a protected way.
- Each and every JSON Web Token (JWT) enclosed with the JSON objects comprises the set of Claims. JWT tokens are signed using Cryptographic Algorithm; once the token is issued, make sure that the Claims are cannot be changed.
ASP.NET Core JWT
The JSON Web Token (JWT) is the Open-Standard which is used to share the security data between Client and Server as a JSON Object in a protected and compressed method. The transmission of data using JWT between the parties is digitally signed to be simply confirmed and confidential.
The creation of JWT with ASP.NET Core Web Application, to create the application by using the Visual Studio or by using the Command Line Interface (CLI),
Use the following command in the command line, which builds the ASP.NET Web API Project with the Name of “JWTAuthentication” in the current folder.
Code:
dotnet new webapi -n JWTAuthentication
The initial step is to configure the JWT authentication in the project; we must register the JWT authentication schema using the “AddAuthentication” procedure and specify the JwtBearerDefaults.AuthenticationScheme, here to configure the authentication schema with JWT bearer options.
Code:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});
services.AddMvc();
}
In the above code, we have seen that the parameters must be taken into account to consider JWT as valid.
- To create the token, just Validate Server (ValidateIssuer=true).
- To validate the recipient token which is authorized to receive it (ValidateAudience=true).
- To confirm whether the token does not get expired and a signing key of the issuer is valid.
- (ValidateLifeTime=true).
- To validate the token signature (ValidateIssuerSigningKey=true).
- In Addition, denote the values of the issuer, signing key, audience. In this example have mentioned the values of the appsettings.json file.
AppSetting.Json:
Code:
{
"Jwt": {
"Key": "ThisismySecretKey",
"Issuer": "Test.com"
}
}
The above-specified steps for configuring the JWT authentication service. Next to make the authentication service which avails for application. We require to call app.UseAuthentication() way for configuring method in startup class. The method UseAuthentication method is called once before the UseMvc Method.
Code:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
app.UseMvc();
}
Specifically ASP.NET JWT
To set up the JWT Authentication and Authorization.
The initial step is to configure the authentication in Startup.ConfigureServices(). To configure the JWT token set-up and include the needed components in the ASP.NET pipeline process.
Code:
// the following code in ConfigureServices()
// the reference values of config
config.JwtToken.Issuer = "https://mysite.com";
config.JwtToken.Audience = "https://mysite.com";
config.JwtToken.SigningKey = "12345@4321"; // defining the login_id
// to configure the Authentication
services.AddAuthentication( auth=>
{
auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
auth.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = config.JwtToken.Issuer,
ValidateAudience = true,
ValidAudience = config.JwtToken.Audience,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey (Encoding.UTF8.GetBytes (config.JwtToken.SigningKey))
};
}
In JWT authentication, there will be a ton of setting that are mostly cryptic to observe it. In general, to store the values in my app’s config settings, so it gets pulled through .NET’S Config provider and .config is the specific configuration instance.
Reasons to Use JWT in Application
Let’s see the implementation of the ASP.NET Core Web API Application by using the JWT Authentication and Authorization. The APIs like Login, Refresh-Token, Impersonation, Logout, and so on.
Given below is the flow of the JWT work procedure as follows:
- Initially, the user sends the credentials to the login process.
- The credentials will be validated from the web page back end, declare the proper claims, and then creates the JWT and return to the user.
- Until the JWT expires, the user will hold on to it and send the JWT to the webpage in consequent requests.
- The Webpage validates the JWT and then decides the resource which is accessible, and then it processes the requests.
- Through this, we came to know this safety measure of JWT importance, so people often recommend sending of JWT’s through HTTP’s and access tokens of JWT.
For the Token generation and login process, just create the JwtAuthManager class to put in entire utilities related to the JWT access token and refresh tokens.
Code:
public class JwtAuthManager : IJwtAuthManager
{
public IImmutableDictionary<string, RefreshToken> UsersRefreshTokensReadOnlyDictionary => _usersRefreshTokens.ToImmutableDictionary();
private readonly ConcurrentDictionary<string, RefreshToken> _usersRefreshTokens; // it refers to store in a database or to store in a distributed cache
private readonly JwtTokenConfig _jwtTokenConfig;
private readonly byte[] _secret;
public JwtAuthManager(JwtTokenConfig jwtTokenConfig)
{
_jwtTokenConfig = jwtTokenConfig;
_usersRefreshTokens = new ConcurrentDictionary<string, RefreshToken>();
_secret = Encoding.ASCII.GetBytes(jwtTokenConfig.Secret);
}
public JwtAuthResult GenerateTokens(string username, Claim[] claims, DateTime now)
{
var shouldAddAudienceClaim = string.IsNullOrWhiteSpace(claims?.FirstOrDefault(x => x.Type == JwtRegisteredClaimNames.Aud)?.Value);
var jwtToken = new JwtSecurityToken(
_jwtTokenConfig.Issuer,
shouldAddAudienceClaim ? _jwtTokenConfig.Audience : string.Empty,
claims,
expires: now.AddMinutes(_jwtTokenConfig.AccessTokenExpiration),
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(_secret), SecurityAlgorithms.HmacSha256Signature));
var accessToken = new JwtSecurityTokenHandler().WriteToken(jwtToken);
var refreshToken = new RefreshToken
{
UserName = username,
TokenString = GenerateRefreshTokenString(),
ExpireAt = now.AddMinutes(_jwtTokenConfig.RefreshTokenExpiration)
};
_usersRefreshTokens.AddOrUpdate(refreshToken.TokenString, refreshToken, (s, t) => refreshToken);
return new JwtAuthResult
{
AccessToken = accessToken,
RefreshToken = refreshToken
};
}
private static string GenerateRefreshTokenString()
{
var randomNumber = new byte[32];
using var randomNumberGenerator = RandomNumberGenerator.Create();
randomNumberGenerator.GetBytes(randomNumber);
return Convert.ToBase64String(randomNumber);
}
}
In this GenerateTokens method, it builds the JWT access token and the refresh token. Here it passes the user level claims into the Payload in JWT access token and sets the exact values for JWT token validation attributes. The refresh tokens are nothing but random strings but enhance the objects of RefreshToken with username and expiration time. To attach the metadata with RefreshToken objects, like Client IP, Device ID, User-Agent, and so on, by using this, we can identify and observe the fake tokens and user session.
Recommended Articles
We hope that this EDUCBA information on “ASP.NET Core JWT” was beneficial to you. You can view EDUCBA’s recommended articles for more information.