Hand in hand teaching you aspnetcore webapi authentication and authorization methods



In recent days, Xiao Ming has trouble again. Before, he didn’t give Xiao Hong the authentication and authorization, so he ran naked online. After being found by boss Ma, he scolded him severely and asked Xiao Ming to add the authorization. Quickly Baidu, found that everyone is using JWT authentication authorization, this is quite suitable for their own.

What is a token

A token is a string generated by the server, which is used as a token for the client to request. After the first login, the server generates a token and returns it to the client. In the future, the client only needs to bring the token to request data without bringing the user name and password again.

What is JWT

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

JWT certification process

As can be seen from the figure, it mainly consists of two parts: 1. Obtaining token; 2. Authorization through token.

Using JWT authentication

First, install the jwtbearer package.

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer --version 3.1.0

Next, define a configuration class. Here, I directly replace it with constants for simplicity. You can also put it in the configuration file.

public class TokenParameter
 Public const string issuer = "depth code farm"; // issuer  
 Public const string audience = depth code farm; // recipient  
 Public const string secret = "12345678123456778"; // signature key  
 Public const int accessexpiration = 30; // accesstoken expiration time (minutes)

Next, define a controller to obtain token through user name and password.

public class OAuthController : ControllerBase
 /// <summary>
 ///Get token
 /// </summary>
 /// <returns></returns>
 public ActionResult GetAccessToken(string username, string password)
  //Here is the user's account and password verification. I've missed it here.
  if (username != "admin" || password != "admin")
   return BadRequest("Invalid Request");

  var claims = new[]
   new Claim(ClaimTypes.Name, username),
   new Claim(ClaimTypes.Role, ""),

  var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(TokenParameter.Secret));
  var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
  var jwtToken = new JwtSecurityToken(TokenParameter.Issuer, TokenParameter.Audience, claims, expires: DateTime.UtcNow.AddMinutes(TokenParameter.AccessExpiration), signingCredentials: credentials);
  var token = new JwtSecurityTokenHandler().WriteToken(jwtToken);

  return Ok(token);

Next, add token authentication to the container( Startup.ConfigureServices )。

services.AddAuthentication(x =>
 x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
 x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
 x.RequireHttpsMetadata = false;
 x.SaveToken = true;
 x.TokenValidationParameters = new TokenValidationParameters
  Validateissuersigningkey = true, // whether to call the SecurityKey of the signing securitytoken for verification
  IssuerSigningKey = new SymmetricSecurityKey( Encoding.ASCII.GetBytes ( TokenParameter.Secret )), // signature key
  Validateissuer = true, // verify the issuer
  ValidIssuer =  TokenParameter.Issuer , // issuer
  Validateaudience = true, // verify the receiver
  ValidAudience =  TokenParameter.Audience , // recipient
  Validatelife time = true, // verify the expiration time

Next, add authentication to middleware( Startup.Configure )。

app.UseAuthentication (); // must be in app.UseAuthorization (); before

Next, the controller needs to authorize the addition of control.

public async Task<ActionResult<Todo>> GetTodo(Guid id)
 var todo = await context.Todo.FindAsync(id);

 if (todo == null)
  return NotFound();

 return todo;

Finally, we test the interface and the results are as follows.

At this time, 401 will be returned, because the authentication failed, indicating that the authentication is effective.

Next, let’s visit the getaccesstoken interface, get the token, and put the token when accessing the gettodo interface. We can see that the access is successful.


So far, Xiao Ming has finished the authorization and certification. Let’s report to boss ma. Of course, the authorization is very simple. There are still many waiting partners to explore, such as how to automatically refresh the token? How to force token invalidation? OAuth, other implementation methods and so on? If you are interested, let Xiao Ming tell you next time.

Here is the article about how to teach you aspnetcore webapi authentication and authorization. For more information about aspnetcore webapi authentication and authorization, please search previous articles of developer or continue to browse the following articles. I hope you can support developer more in the future!