Vis*_*edi 5 c# asp.net-core-mvc asp.net-core jwt-auth
我最近一直在学习ASP.NET Core 2.2,并尝试使用JWT令牌开发基于角色的登录示例(网站+ Web API)。
定义很简单:
但是,我在“带有ASP.NET Core 2.2的JWT令牌”上找到的大多数解决方案和文章仅适用于Web API。
从下面的文章中,我几乎了解了JWT令牌的工作原理以及如何在Web API上实现它:
现在我的问题是如何使用ASP.NET Core网站使用上述API?
对于许多人来说,这可能是一个简单的问题,但是我对Web开发还很陌生,并且不了解很多事情。
任何帮助,将不胜感激。提前致谢。
使用我在评论中发布的指南。这不是您所需要的全部 - 但我无法在评论中发布代码。需要长格式。
您可以使用声明将角色放入您的令牌中。
在你的startup.cs中
var secretKey = Configuration.GetSection("JWTSettings:SecretKey").Value;
var issuer = Configuration.GetSection("JWTSettings:Issuer").Value;
var audience = Configuration.GetSection("JWTSettings:Audience").Value;
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = issuer,
ValidateAudience = true,
ValidAudience = audience,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
};
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = tokenValidationParameters;
});
Run Code Online (Sandbox Code Playgroud)
然后在用户用来“登录”或发出令牌的控制器方法中。
var claims = new[] {
new Claim(ClaimTypes.Name, Credentials.Email),
new Claim(ClaimTypes.Role, Role) };
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.SecretKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _options.Issuer,
audience: _options.Audience,
claims: claims,
expires: DateTime.Now.AddYears(10),
signingCredentials: creds);
Run Code Online (Sandbox Code Playgroud)
然后用该角色保护您的方法或控制器。
[Authorize(Roles = "Admin")]
[HttpGet]
Public IActionResult GrabStuff(){ }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2680 次 |
| 最近记录: |