1.安装jwt nuget

    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.25" />
    <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.0.3" />

1.1创建jwt配置

namespace webapi
{
    /// <summary>
    /// 有效载荷配置信息
    /// </summary>
    public class JwtTokenOption
    {
        /// <summary>
        /// Token 过期时间默认为60分钟
        /// </summary>
        public int TokenExpireTime { get; set; } = 60;

        /// <summary>
        /// 接收
        /// </summary>
        public string Audience { get; set; }

        /// <summary>
        /// 秘钥(RSA)
        /// </summary>
        public string SecurityKey { get; set; }

        /// <summary>
        /// 签发人
        /// </summary>
        public string Issuer { get; set; }
    }
}

2.配置jwt信息

//注入jwt配置服务
            var jwtOption = builder.Configuration.GetSection("JwtTokenOption");
            builder.Services.Configure<JwtTokenOption>(jwtOption);
            JwtTokenOption jwtTokenOption = jwtOption.Get<JwtTokenOption>();

            //认证
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwtBearerOptions =>
            {
                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidAlgorithms = new string[] { "HS256" },//对称加密
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtTokenOption.SecurityKey)),//拿到SecurityKey
                    ValidateIssuer = true,//是否验证Issuer
                    ValidateAudience = true,//是否验证Audience
                    ValidateLifetime = false,//是否验证失效时间
                    ClockSkew = TimeSpan.FromSeconds(30),//时钟脉冲相位差
                    ValidateIssuerSigningKey = true,//是否验证SecurityKey
                    ValidAudience = jwtTokenOption.Audience,//Audience
                    ValidIssuer = jwtTokenOption.Issuer,//Issuer,这两项和前面签发jwt的设置一致
                };
            });;

3.生成token

    [HttpPost("{username}")]
        [AllowAnonymous]
        public IActionResult tokensc()
        {
            // 有效载荷,大家可以自己写,爱写多少多少;尽量避免敏感信息
            var claims = new[]
            {
            new Claim(ClaimTypes.Name, "pzx"),
            new Claim("NickName","aa"),
            new Claim("Role","Administrator"),//传递其他信息
            };

            // payload 中的信息声明
            var jwtSecurityToken = new JwtSecurityToken(
                claims: claims,
                expires: DateTime.Now.AddMinutes(_jwtTokenOption.TokenExpireTime),
                signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_jwtTokenOption.SecurityKey)), SecurityAlgorithms.HmacSha256),
                issuer: _jwtTokenOption.Issuer,
                audience: _jwtTokenOption.Audience);
                var tokenString = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken); ;
                return Ok(tokenString);
        }

4.在需要的控制器方法上,使用过滤器(只有token解析成功,没有过期才可以访问接口)

[Authorize]
[HttpGet]
public IActionResult Get(){
return ok();
}

5.可以结合IdentityService4身份认证框架使用

原文地址:https://blog.csdn.net/qq_41942413/article/details/134680803

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_32812.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注