Add jwtbearer certification to. Net 5 API



JWT is the abbreviation of JSON web token. JWT is a JSON based open standard implemented to transfer declarations between network application environments(RFC 7519)。 The token is designed to be compact and secure, especially suitable for single sign on (SSO) scenarios of distributed sites. The declaration of JWT is generally used to transfer the authenticated user identity information between identity providers and service providers, so as to obtain resources from the resource server. Some additional declaration information necessary for other business logic can also be added. The token can also be directly used for authentication or encrypted.

Installation package reference

Here we need to install two nuget packages, so please install them through the nuget management tool before starting:

Microsoft.AspNetCore.Authentication.JwtBearerThis is used for JWT token generation and authentication.Swashbuckle.AspNetCoreThis makes it easy to call the modal API in the development environment.

Add Authentication

Next, let’s addJwtBearerAuthentication, openStartup.csFile, and thenConfigureServices(IServiceCollection services)Add the following code to the method:

    .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
        options.TokenValidationParameters = new TokenValidationParameters()
            ValidateIssuer = true,
            ValidIssuer = "Security:Tokens:Issuer",
            ValidateAudience = true,
            ValidAudience = "Security:Tokens:Audience",
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Security:Tokens:Key"))

In this way, the system supportsJWTAfter authentication, you can add JWT authentication to the API to use authentication. Add on APIAuthorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)You can:

[HttpGet("Get"), Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public IEnumerable Get()
    var rng = new Random();
    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        Date = DateTime.Now.AddDays(index),
        TemperatureC = rng.Next(-20, 55),
        Summary = Summaries[rng.Next(Summaries.Length)]

Generate JWT token

Now?GetThe API can only be called after authentication, so we need to generate a JWT token and bring this token when calling the API, so that we can call the API.

Let’s write oneBuildTokenPrivate method for generating the user’s ID into a token:

private string BuildToken(string userId)
    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes("Security:Tokens:Key");
    var tokenDescriptor = new SecurityTokenDescriptor
        Issuer = "Security:Tokens:Issuer",
        Audience = "Security:Tokens:Audience",
        Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, userId) }),
        Expires = DateTime.UtcNow.AddDays(7),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256)
    var token = tokenHandler.CreateToken(tokenDescriptor);
    return tokenHandler.WriteToken(token);

Write another API to return the token. In the actual project, you can confirm the user through the user name and password, and then return the corresponding token after successful confirmation. Here, for convenience, just go back directlyadminUser’s Token:

public IActionResult GetToken()
    return Ok(new { Token = BuildToken("admin") });

Call API using swagger

The JWT authentication of API has been configured. Next, let’s configure itswagger, swagger can easily call the API.

Also openStartup.csFile, and inConfigureServices(IServiceCollection services)Add the following code to the method:

services.AddSwaggerGen(c =>
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebAPI", Version = "v1" });
    var securityScheme = new OpenApiSecurityScheme
        Name = "JWT Authentication",
        Description = "Enter JWT Bearer token **_only_**",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.Http,
        Scheme = "bearer", 
        BearerFormat = "JWT",
        Reference = new OpenApiReference
            Id = JwtBearerDefaults.AuthenticationScheme,
            Type = ReferenceType.SecurityScheme
    c.AddSecurityDefinition(securityScheme.Reference.Id, securityScheme);
    c.AddSecurityRequirement(new OpenApiSecurityRequirement
        { securityScheme, new string[] { } }

Then inConfigure(IApplicationBuilder app, IWebHostEnvironment env)Add the following code to the method:

app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebAPI v1"));

This completes all configuration. Run the project for testing.

Test API

Let’s test it directly firstGetAPI, click “try it out”:

Then click “execute”:




The API returns 401, indicating that the API cannot be called successfully now, and authentication is required:





Get token

We callGetTokenAPI to get token:


Then copy the token content. Be careful not to copy the whole result. Just copy the token value:




Then click “authorize”, paste the token just copied, and then click authorize,





Let’s call againGetTry the API. Now you can call it successfully:





Complete source code:

Original address:

Recommended Today

SQL statement of three-level linkage of provinces, cities and counties

The first is the table creation statement Copy codeThe code is as follows: CREATE TABLE `t_address_province` ( `id` INT AUTO_ Increment primary key comment ‘primary key’,`Code ` char (6) not null comment ‘province code’,`Name ` varchar (40) not null comment ‘province name’)Engine = InnoDB default charset = utf8 comment = ‘province information table’; CREATE TABLE […]