标签:sch mic parameter home col 获取 服务 and route
VS创建WebApi nuget引用jwt的包
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer -Version 3.1.3
新建一个类JwtAuthorization.cs用于编写Jwt的验证服务
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<IHttpResponseFeature>().ReasonPhrase = context.Exception.Message;
return Task.CompletedTask;
},
OnTokenValidated = context =>
{
return Task.CompletedTask;
}
};
});
}
在Startup类ConfigureServices方法里注册JwtAuthorizationStartup
services.JwtAuthorizationStartup();
在Startup类Configure方法里启用授权验证
app.UseAuthentication();
app.UseAuthorization();
创建Login控制器添加三个动作获取三个角色的token
[ApiController]
[Route("[controller]")]
public class LoginController : ControllerBase
{
private readonly ILogger<LoginController> _logger;
public LoginController(ILogger<LoginController> logger)
{
_logger = logger;
}
[HttpPost("System")]
public IActionResult System()
{
Claim[] claims = new[]
{
new Claim(ClaimTypes.Sid,"1"),
new Claim(ClaimTypes.Name, "张三"),
new Claim(ClaimTypes.Email,"net*****@163.com"),
new Claim(ClaimTypes.Role, "System"),
};
//密钥
SymmetricSecurityKey signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("1234567890123456"));
SigningCredentials signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
JwtSecurityToken jwtSecurityToken = new JwtSecurityToken
(
issuer: "DUST",
audience: "DUST",
claims: claims,
expires: DateTime.Now.AddDays(7),
signingCredentials: signingCredentials
);
string token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
return Ok(token);
}
[HttpPost("Admin")]
public IActionResult Admin()
{
Claim[] claims = new[]
{
new Claim(ClaimTypes.Sid,"1"),
new Claim(ClaimTypes.Name, "张三"),
new Claim(ClaimTypes.Email,"net*****@163.com"),
new Claim(ClaimTypes.Role, "System"),
};
//密钥
SymmetricSecurityKey signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("1234567890123456"));
SigningCredentials signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
JwtSecurityToken jwtSecurityToken = new JwtSecurityToken
(
issuer: "DUST",
audience: "DUST",
claims: claims,
expires: DateTime.Now.AddDays(7),
signingCredentials: signingCredentials
);
string token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
return Ok(token);
}
[HttpPost("Client")]
public IActionResult Client()
{
Claim[] claims = new[]
{
new Claim(ClaimTypes.Sid,"1"),
new Claim(ClaimTypes.Name, "张三"),
new Claim(ClaimTypes.Email,"net*****@163.com"),
new Claim(ClaimTypes.Role, "System"),
};
//密钥
SymmetricSecurityKey signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("1234567890123456"));
SigningCredentials signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
JwtSecurityToken jwtSecurityToken = new JwtSecurityToken
(
issuer: "DUST",
audience: "DUST",
claims: claims,
expires: DateTime.Now.AddDays(7),
signingCredentials: signingCredentials
);
string token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
return Ok(token);
}
}
添加一个Home控制器标注控制器的角色有两种写法一种是默认的基于角色授权,这里用的第二种基于策略的授权
[Route("api/[controller]")]
[ApiController]
//[Authorize(Roles = "Admin,System")]
[Authorize(policy: "AdminOrSystem")]//使用策略的授权的好处就是不用在controller中,写多个 roles
public class HomeController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok("Client");
}
}
然后在postman测试 Demo下载
标签:sch mic parameter home col 获取 服务 and route
原文地址:https://www.cnblogs.com/SuperDust/p/12764065.html