Skip to content

RsCode.AspNetCore提供JwtHelper,帮助生成token

1.自定义授权请求类

csharp
 public class SellerRequirement : IAuthorizationRequirement
    { }
    public class SellerRequirementHandler : AuthorizationHandler<SellerRequirement>
    {
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, SellerRequirement requirement)
        {
            if (context.User.Claims.Count() > 0)
            {
                var shopId = context.User.Claims.FirstOrDefault(c => c.Type == "ShopId")?.Value;
                if (string.IsNullOrWhiteSpace(shopId))
                {
                    context.Fail();
                }
                else
                { 
                   context.Succeed(requirement);
                }
            }
        }
    }

2.注册授权服务

csharp
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    var jwt = JwtHelper.GetJwtInfo();
                    jwt.Expire = jwt.Expire * 60;
                    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                    {
                        ValidateIssuer = true,//是否验证发行者
                        ValidateAudience = true,//是否验证接收者
                        ValidateLifetime = true,//是否验证失效时间
                        ClockSkew = TimeSpan.FromMinutes(jwt.Expire),
                        ValidateIssuerSigningKey = true,//是否验证安全key
                        ValidAudience = jwt.Audience,//有效的接收者
                        ValidIssuer = jwt.Issuer,//有效的发行者 
                        IssuerSigningKey =
                        new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.SecurityKey))
                    }; 
                });


services.AddAuthorization(options =>
{         
    options.AddPolicy("seller", policy => policy.RequireClaim("ShopId"));
});

services.TryAddSingleton<IAuthorizationHandler, SellerRequirementHandler>();
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

3.在appsetting.json中配置

json
{
"Jwt": {
    "Issuer": "https://rscode.cn",
    "Audience": "rscode.cn",
    "SecurityKey": "12343543DFSSDAFDFI2xxxxxxxxxx",
    //accesstoken过期时间,单位(分钟)
    "Expire": 15
  }
}

使用claim创建accesstoken

csharp
var token=JwtHelper.CreateAccessToken(claims,60*24*7);

需要授权的地方,添加[Authorize][Authorize("seller")]