Loading

在.NET5中 使用JWT鉴权授权

1、创建一个单独的WebApi项目用作JWT服务,直接使用主服务创建一个控制器也可

2、安装包

PM> Install-Package System.IdentityModel.Tokens.Jwt

3、JWT授权

在登录接口或其它你想颁发Token的地方编写如下Token生成代码
var claims = new Claim[]
            {
                new Claim(ClaimTypes.Name, author.Name),
                new Claim("Id",author.Id.ToString()),
                new Claim("UserName",author.UserName)
            };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF-VF"));
                //issuer代表颁发Token的Web应用程序,audience是Token的受理者
                var token = new JwtSecurityToken(
                    issuer: "http://localhost:6060",
                    audience: "http://localhost:5000",
                    claims: claims,
                    notBefore: DateTime.Now,
                    expires: DateTime.Now.AddHours(1),
                    signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
                );
                var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
                return ApiResultHelper.Success(jwtToken);

4、JWT鉴权

安装包

PM> Install-Package Microsoft.AspNetCore.Authentication.JwtBearer

注册服务到容器中

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF-VF")),
                    ValidateIssuer = true,
                    ValidIssuer = "http://localhost:6060",
                    ValidateAudience = true,
                    ValidAudience = "http://localhost:5000",
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.FromMinutes(60)
                };
            });

5、JWT授权鉴权使用

Swagger想要使用鉴权需要注册服务的时候添加以下代码

//丝袜哥使用鉴权组件
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    Description = "直接在下框中输入WeBlog {token}(注意两者之间是一个空格)",
                    Name = "Authorization",
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
        {
          {
            new OpenApiSecurityScheme
            {
              Reference=new OpenApiReference
              {
                Type=ReferenceType.SecurityScheme,
                Id="Bearer"
              }
            },
            new string[] {}
          }
        });

记得添加用户认证组件到管道中

app.UseAuthentication();
app.UseAuthorization();

最后在需要鉴权的接口或者控制器上使用注解即可

需要鉴权
[Authorize]

不需要鉴权
[AllowAnonymous]

代码:https://github.com/luchong0813/WeBlog

posted @ 2021-11-24 22:38  傲慢与偏见luc  阅读(467)  评论(0编辑  收藏  举报