C# ASP.NET Core Web API Identity Authorization (JWT) Verification (1)

1. The development environment is VS2022. When installing, remember to check all ASP.NET-related items. It is recommended to select all to save trouble.

        

2. Create the initial project TestApi (your own project name).

 

 This means that the project is successfully created, and you can debug by pressing F5.

In the project, we will not only use basic api functions, but we will also generally use  identity authorization (JWT) , Redis cache , MySQL database , etc. Today we will only talk about identity authorization (JWT) . The following article will continue to explain the other two items.

-------------------- Add  Identity Authorization (JWT) --------------------

Right-click on the project and select Manage NuGet Packages:

Enter Microsoft.AspNetCore.Authentication.JwtBearer in the search box on the browse page

Click to install (pay attention to the version, choose the major version 6):

 

 After the installation is complete, open the project appsettings.json configuration file and add JWT configuration:

  "Jwt": {
    "SecretKey": "u6u^Bdob@OJ&KF2RcAB%ybsoy&2S7jhP^SW!q!Z^FK7eB7F8CcxIHsIh4Ll3pL^#",
    "Issuer": "WebAppIssuer",
    "Audience": "WebAppAudience"
  }

 The next step is to add the folder Common under the project directory:

 Add the JWTHelper.cs class in the Common folder:

 Complete code (where the namespace namespace TestApi.Common can be changed to your own):

using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace TestApi.Common
{
    /// <summary>
    /// 授权JWT类
    /// </summary>
    public class JwtHelper
    {
        private readonly IConfiguration _configuration;

        /// <summary>
        /// Token配置
        /// </summary>
        /// <param name="configuration"></param>
        public JwtHelper(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// 创建Token 这里面可以保存自己想要的信息
        /// </summary>
        /// <param name="username"></param>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public string CreateToken(string username,string mobile)
        {
            // 1. 定义需要使用到的Claims
            var claims = new[]
            {
            new Claim("username", username),
            new Claim("mobile", mobile),
            /* 可以保存自己想要信息,传参进来即可
            new Claim("sex", "sex"),
            new Claim("limit", "limit"),
            new Claim("head_url", "xxxxx")
            */
        };

            // 2. 从 appsettings.json 中读取SecretKey
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"]));

            // 3. 选择加密算法
            var algorithm = SecurityAlgorithms.HmacSha256;

            // 4. 生成Credentials
            var signingCredentials = new SigningCredentials(secretKey, algorithm);

            // 5. 根据以上,生成token
            var jwtSecurityToken = new JwtSecurityToken(
                _configuration["Jwt:Issuer"],    //Issuer
                _configuration["Jwt:Audience"],  //Audience
                claims,                          //Claims,
                DateTime.Now,                    //notBefore
                DateTime.Now.AddSeconds(30),     //expires
                signingCredentials               //Credentials
            );

            // 6. 将token变为string
            var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

            return token;
        }
    }

}

Open the Program.cs file and add registration information:

#region JWT服务
// 注册JWT服务
builder.Services.AddSingleton(new JwtHelper(builder.Configuration));

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}
).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters()
    {
        ValidateIssuer = true, //是否验证Issuer
        ValidIssuer = builder.Configuration["Jwt:Issuer"], //发行人Issuer
        ValidateAudience = true, //是否验证Audience
        ValidAudience = builder.Configuration["Jwt:Audience"], //订阅人Audience
        ValidateIssuerSigningKey = true, //是否验证SecurityKey
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:SecretKey"])), //SecurityKey
        ValidateLifetime = true, //是否验证失效时间
        ClockSkew = TimeSpan.FromSeconds(30), //过期时间容错值,解决服务器端时间不同步问题(秒)
        RequireExpirationTime = true,
    };
}
);
#endregion

 

 Add the Models folder, and then the UserInfo.cs class:

The complete code is as follows:

using System.ComponentModel.DataAnnotations;

namespace TestApi.Models
{
    public class UserInfo
    {
        /// <summary>
        /// 其中 [Required] 表示非空判断,其他自己研究百度
        /// </summary>
        [Required]
        public string UserName { get; set; }
        [Required]
        public string Password { get; set; }
        [Required]
        public string PhoneNumber { get; set; }

    }
}

Add the API controller UserInfoController.cs in the Controllers folder

 Full code:

using Microsoft.AspNetCore.Mvc;
using TestApi.Common;
using TestApi.Models;

namespace TestApi.Controllers
{
    [Route("[controller]/[action]")]
    [ApiController]
    public class UserInfoController : ControllerBase
    {
        private readonly JwtHelper _jwt;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="jwtHelper"></param>
        public UserInfoController(JwtHelper jwtHelper)
        {
            _jwt = jwtHelper;
        }
        /// <summary>
        /// 获取Token
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetToken(UserInfo user)
        {
            //参数验证等等....
            if (string.IsNullOrEmpty(user.UserName))
            {
                return Ok("参数异常!");
            }

            //这里可以连接mysql数据库做账号密码验证


            //这里可以做Redis缓存验证等等


            //这里获取Token,当然,这里也可以选择传结构体过去
            var token = _jwt.CreateToken(user.UserName, user.PhoneNumber);
            return Ok(token);
        }

        /// <summary>
        /// 获取自己的详细信息,其中 [Authorize] 就表示要带Token才行
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public IActionResult GetSelfInfo()
        {
            //执行到这里,就表示已经验证授权通过了
            /*
             * 这里返回个人信息有两种方式
             * 第一种:从Header中的Token信息反向解析出用户账号,再从数据库中查找返回
             * 第二种:从Header中的Token信息反向解析出用户账号信息直接返回,当然,在前面创建        Token时,要保存进使用到的Claims中。
            */
            return Ok("授权通过了!");
        }
    }
}

 Then, you can F5 test:

​​​​​​​

The next article will continue to introduce Redis:

C# ASP.NET Core Web API Redis tutorial (2) - asp.net redis tutorial - blog

Guess you like

Origin blog.csdn.net/u012402739/article/details/128463873