Asp.Net Core 使用 Jwt
2021-03-19 01:24
标签:sch mic parameter home col 获取 服务 and route VS创建WebApi nuget引用jwt的包 新建一个类JwtAuthorization.cs用于编写Jwt的验证服务 在Startup类ConfigureServices方法里注册JwtAuthorizationStartup 在Startup类Configure方法里启用授权验证 创建Login控制器添加三个动作获取三个角色的token 添加一个Home控制器标注控制器的角色有两种写法一种是默认的基于角色授权,这里用的第二种基于策略的授权 然后在postman测试 Demo下载 Asp.Net Core 使用 Jwt 标签:sch mic parameter home col 获取 服务 and route 原文地址:https://www.cnblogs.com/SuperDust/p/12764065.htmlJwt全称josn web token,生成token支持多种语言,token的方式做登录身份校验
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer -Version 3.1.3
public static void JwtAuthorizationStartup(this IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
//授权角色
services.AddAuthorization(options =>
{
options.AddPolicy("Client", policy => policy.RequireRole("Client").Build());
options.AddPolicy("AdminOrSystem", policy => policy.RequireRole("Admin", "System").Build());
});
//密钥加密
SymmetricSecurityKey signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("1234567890123456"));
SigningCredentials signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
// 令牌验证参数
TokenValidationParameters tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = "DUST",//发行人
ValidateAudience = true,
ValidAudience = "DUST",//订阅人
ValidateLifetime = true,
ClockSkew = TimeSpan.FromSeconds(30),
RequireExpirationTime = true,
};
// 认证jwt
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = tokenValidationParameters;
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
context.NoResult();
context.Response.StatusCode = 401;
context.Response.HttpContext.Features.Get
services.JwtAuthorizationStartup();
app.UseAuthentication();
app.UseAuthorization();
[ApiController]
[Route("[controller]")]
public class LoginController : ControllerBase
{
private readonly ILogger
[Route("api/[controller]")]
[ApiController]
//[Authorize(Roles = "Admin,System")]
[Authorize(policy: "AdminOrSystem")]//使用策略的授权的好处就是不用在controller中,写多个 roles
public class HomeController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok("Client");
}
}
下一篇:HTML 04超链接标签
文章标题:Asp.Net Core 使用 Jwt
文章链接:http://soscw.com/index.php/essay/66016.html