Hand-on AspNetCore WebApi: Authentication and Authorization

Reference web address: https://www.cnblogs.com/zcqiand/p/13799124.html


Xiao Ming is troubled again these days. Before that, he did not authorize Xiao Hong's interface to be certified. He ran naked online and was scolded severely by the owner of Ma when he discovered it. He immediately asked Xiao Ming to add the authorization. Hurry up Baidu and find that everyone is authorized with JWT certification, which is quite suitable for you.

What is Token

Token is a string generated by the server as a token for the client to request. When the server generates a Token after the first login, the server returns the Token to the client. In the future, the client only needs to bring the Token to request data without having to bring the user name and password again.

What is JWT

Json web token (JWT) is a JSON-based open standard ((RFC 7519)) implemented to deliver declarations between network application environments. The token is designed to be compact and secure, especially for single sign-on (SSO) on distributed sites. Scenario. JWT's declaration is typically used to pass authenticated user identity information between the identity provider and the service provider to facilitate resource acquisition from the resource server. It can also add declaration information necessary for additional business logic. The token can also be used directly for authentication or encrypted.

JWT authentication process

From the diagram, we can see that there are two main components: 1, acquiring Token, 2, authorizing through Token.

Use JWT authentication

First, install the JwtBearer package.

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

Next, define a configuration class, which I've replaced with constants for simplicity. You can also put it in a configuration file.

public class TokenParameter
    public const string Issuer = "Deep Yanong";//Issuer        
    public const string Audience = "Deep Yanong";//Recipient        
    public const string Secret = "1234567812345678";//Signature Key        
    public const int AccessExpiration = 30;//AccessToken expiration time (minutes)

Next, define a controller that gets Token by user name and password.

public class OAuthController : ControllerBase
    /// <summary>
    ///Get Token
    /// </summary>
    /// <returns></returns>
    public ActionResult GetAccessToken(string username, string password)
        //User's account password is checked here. I skipped 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 invoke SecurityKey to verify the signature securityToken
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(TokenParameter.Secret)),//Signature Key
        ValidateIssuer = true,//Verify Issuer
        ValidIssuer = TokenParameter.Issuer, //Issuer
        ValidateAudience = true, //Verify Recipient
        ValidAudience = TokenParameter.Audience,//Recipient
        ValidateLifetime = true,//Verify Failure Time

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

app.UseAuthentication();//Must precede app.UseAuthorization();

Next, the controller needs to authorize the addition of control [Authorize].

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

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

    return todo;

Finally, let's test the interface, and the results are as follows.

This returns 401 because the authentication failed, indicating that the authentication worked.

Next we visit the GetAccessToken interface, get the Token, put the Token in when we access the GetTodo interface, and we can see that the access is successful.


So far, Xiao Ming has completed the authorization certification, so let's report the work to Boss Ma. Of course, this authorization certification is still very simple, and there are many waiting partners to discover, such as how to refresh Token automatically? How do I force Token to fail? Other implementations of OAuth, and so on? If you are interested, let Xiao Ming tell you next time.

Classification:   Teach you AspNetCore WebApi by hand

Posted on Sat, 27 Nov 2021 12:04:19 -0500 by neonorange79