ASP.NET Core 2.2 JWT身份验证 [英] ASP.NET Core 2.2 JWT Authentication

查看:97
本文介绍了ASP.NET Core 2.2 JWT身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在学习ASP.NET Core 2.2,并尝试使用JWT令牌开发基于角色的登录示例(网站+ Web API).

I've been learning about ASP.NET Core 2.2 recently and trying to develop a Role-Based login sample(Website + Web API) using JWT token.

定义很简单:

  • 如果用户的角色是管理员",则它将重定向到管理页面.
  • 如果用户的角色是用户",则它将重定向到用户页面.

但是,我在带有ASP.NET Core 2.2的JWT令牌"上找到的大多数解决方案和文章仅适用于Web API.

But most of the solutions and articles I found on "JWT token with ASP.NET Core 2.2" is only for Web API.

从下面的文章中,我几乎了解了JWT令牌的工作原理以及如何在Web API端实现它:

I've almost understood how JWT token works and how to implement it on Web API side from following article :

http://jasonwatmore.com/post/2019/01/08/aspnet-core-22-role-based-authorization-tutorial-with-example-api

现在我的问题是如何使用ASP.NET Core网站使用上述API?

Now my problem is how to consume above API using ASP.NET Core Website?

对于许多人来说,这可能是一个简单的问题,但是我对Web开发还很陌生,并且不了解很多事情.

This might be a simple problem for many a guys but I'm fairly new to web development and don't understand a lot of things.

任何帮助将不胜感激. 预先感谢.

Any help would be appreciated. Thanks in advance.

推荐答案

使用我在评论中发布的指南.这不是您所需要的全部-但是我无法在注释中发布代码.需要长格式.

Using the guide i posted in the comments. This isn't all you need - but i cant post code in comments. Needed long form.

您使用声明将角色添加到令牌中.

You use claims to get the role into your token.

在您的startup.cs

In your 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;
    });

然后在控制器方法中,用户用于登录"或发出令牌.

Then in your controller method that a user uses to "login" or issue a token.

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);

然后使用该角色保护您的方法或控制器.

Then protect your method or controller with the role.

 [Authorize(Roles = "Admin")]
   [HttpGet]
   Public IActionResult GrabStuff(){ }

这篇关于ASP.NET Core 2.2 JWT身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆