JWT不管是基于角色,还是自定义策略,实现的步骤都是大同小异的,基于自定义策略的步骤如下:

  1、appsettings.json中配置JWT参

  2、添加身份认证和授权服务和中间件,并设置为策略模式和策略名称

  3、定义生成Token的方法和验证Toekn参数的方法

  4、登录时验证身份并分发Toekn

  5、继承AuthorizationHandler<IAuthorizationRequirement>,实现鉴权的规则

  接下来看看具体实现。

 

JWT配置

"JWTConfig": {
"Secret": "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890",
"Issuer": "gsw",
"Audience": "everone",
"Expires": 10000
}

实现自定义策略

using).Bind(jwtConfig);
builder.Services.AddSingleton(jwtConfig);
//这里是注入权限数据,也可以放在缓存中,以便鉴权时用
builder.Services.AddSingleton(new List<Permission> { new Permission { RoleName = "admin", Url = "/helloadmin", Method = "get"();
//注入身分验证和授权,并且是Policy的名称为Permission
builder.Services
.AddAuthorization(options =>;
opt.TokenValidationParameters =;
logger.LogInformation(message);

return);

app.MapGet("/helloadmin", (ILogger<Program> logger, HttpContext context) =>;
logger.LogInformation(message);
return);

app.MapGet("/helloall", (ILogger<Program> logger, HttpContext context) =>;
logger.LogInformation(message);
return);

//登录,并分发Token
app.MapPost("/login", [AllowAnonymous] (ILogger<Program> logger, LoginModel login, JWTConfig jwtConfig) =>);
if (login.UserName == "gsw" && login.Password == "111111")
{
var now =),
new Claim(ClaimTypes.Name, "桂素伟"),
new;
}
});

app.Run();
//登录实体
public class; }
public string? Password { get; set; }
}
//JWT配置文年
public class; }
public string? Issuer { get; set; }
public string? Audience { get; set; }
public int Expires { get; set; }
}
//Token功能类
public class,
AccessToken =);
var signingKey = new);
var signingKey = new,
IssuerSigningKey =,
ValidIssuer = jwtConfig?.Issuer,
ValidateAudience = true,
ValidAudience = jwtConfig?.Audience,
ClockSkew =,
};
}
}
//权限实本类
public class; }
public string? Url { get; set; }
public string? Method { get; set; }
}
//自定义策略授权时的参数类型,这时没参数,所以是个空类型
public class.Path;
var method = httpContext?.Request?.Method;
var isAuthenticated = context?.User?.Identity?.IsAuthenticated;
if (isAuthenticated.HasValue &&.Value;
if (_userPermissions.Where(w => w.RoleName == role && w.Method?.ToUpper() == method?.ToUpper() && w.Url?.ToLower() == questPath).Count() > 0)
{
context?.Succeed(requirement);
}
else.Fail();
}
}
}
return Task.CompletedTask;
}
}

运行结果如下:

1、没有登录,返回401

.NET6之MiniAPI(十):基于策略的身份验证和授权_微信公众号

2、登录,取token

 

.NET6之MiniAPI(十):基于策略的身份验证和授权_自定义_02

 3、正确访问

.NET6之MiniAPI(十):基于策略的身份验证和授权_自定义_03

 

 4、没有授权访问,返回403

.NET6之MiniAPI(十):基于策略的身份验证和授权_自定义_04

 

  想要更快更方便的了解相关知识,可以关注微信公众号 

.NET6之MiniAPI(十):基于策略的身份验证和授权_微信公众号_05