1. 程式人生 > 其它 >在.NET5中 使用JWT鑑權授權

在.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