Issuing and authenticating JWT tokens in ASP.NET Core WebAPI – Part II

Introduction

本文的例子是你如何使用ASP.NET Core 1来发行你的JWT tokens和通过简单的应用程序,自动控制对持有者的访问使用** [Authorize] **,特别关注基于用户声明授权使用ASP.NET Core MVC的策略特性在一个Web API项目中。

Part I 第一部分讨论了如何发布JWT,在本部分中,我们将介绍授权方面的。

因此,这篇文章的组织如下:

  1. Configuration – 解决需要添加到中间件和服务的问题,以便进行身份验证。
  2. You Shall Not Pass! 我不能帮助我自己,是的,访问控制。
  3. Quick Revision 我们将怎样到底那里。
  4. Authorise 设置一个控制器来测试这些东西。
  5. Testing– 实际上测试了这些东西。
  • Access Granted(允许访问,权利被授予)
  • Access Denied(拒绝访问)

Once again I wish to reiterate(重申) that, if you would like to go straight to(进入) production-ready(生产就绪) frameworks, both IdentityServer as well as OpenIddict are actively developed and maintained.(积极开发和维护)

Requirements

为了理解这篇文章,你很可能需要读第一部分。
however, if you would prefer just getting straight to the code(直接使用代码), you can download/fork(分叉) the example project and reference the relevant sections as we go.(并参考相关章节)

Configuration

首先,我们需要添加基于声明式的授权 claims-based authorisation策略。
This is easily done in the ConfigureServices method in Startup.cs

它所做的就是添加一个策略:DisneyUser,要求DisneyCharacter 声明在传入的token有效负载上有一个IAmMickey的值(稍后我会讲策略是如何应用的)

接下来要做的事,就是告诉ASP.NET,传入的请求会带JWT。幸运的是,有中间件支持(although(尽管) it does require that you add the Microsoft.AspNetCore.Authentication.JwtBearer package as a dependency)

Adding middleware is done in the Configure method of Startup.cs,因为这是在推动授权,它首先需要在中间件管道中添加,
in case(如果) you did not know this,** the order in which you add middlewareis important**

  • Lines 8 – 23:设置我们要传递的参数给ASP.NET'S JWT身份验证 中间件(可以有更多的选择在这里利用,以供参考:TokenValidationParameters live in the Microsoft.IdentityModel.Tokens namespace) I believe the parameters set in this example are reasonably self-explanatory(合理地,不言而喻的。)但是如果有什么不清楚的,请在评论中提问。
  • Lines 25 – 30: add the JWT token bearer(持有者) middleware that tells the application that we expect(希望) JWT tokens as part of the authentication(身份验证) and authorisation processes(授权验证) and to automatically challenge and authenticate.自动调整和验证)。

这就是配置,接下来,限制使用授权策略访问控制器。

You Shall(将) Not Pass!

Quick Revision(快速修测)
  • Part I,I set up claims identities in JwtController.cs and gave the user MickeyMouse, a claim named DisneyCharacter with the value IAmMickey (refer back to lines 110 – 134 of that file).

  • 在上面的Configuration部分中,, I added a DisneyUser authorisation (授权)policy to the services collection(服务集合).

Authorise(授权)

为了测试授权设置,我们需要一个能满足我们请求的服务器,为此,我创建了一个非常基本的JwtAuthTestController.

  • Line 7: 注意控制器的路由配置
  • Lines 20 – 32: 这是控制器中唯一的方法
  • Line 20: 告诉应用程序,该方法期望得到GET请求
  • Line 21: 告诉身份验证中间件把DisneyUser的授权策略用在该方法。这将确保只有满足我们在配置中设置的要求的JWT的持有者才可以访问这个方法
  • Lines 22 – 32: 在控制器中执行一些基本的逻辑并返回响应。
Testing

基本的测试设置和第一部分* Part I*的基本测试是一样的。为了便于参考,我重复这里的说明。

对于测试和验证部分,您需要有一些方法向应用程序发送请求,I am particular to Postman and will be using it throughout.

  1. Fire up the example solution/your application
  2. If you are using the example solution, the application’s URL ishttp://localhost:1783/ (configured in launchSettings.json)
  3. Start up Postman

Access Granted
在我们测试访问之前,我们需要一个无记名令牌来添加我们的请求。

Configure a POST to http://localhost:1783/api/jwt with ‘x-www-form-urlencoded’ selected under **Body. **Provide two key/values for the form, ‘username’ as ‘MickeyMouse’ and ‘password’ as ‘MickeyMouseIsBoss123’ (remember these values are hard coded in the GetClaimsIdentity method on the JwtController)

Issuing and authenticating JWT tokens in ASP.NET Core WebAPI – Part II_第1张图片
Paste_Image.png

Click ‘Send’ and wait (if you are running your solution through VS in Debug mode, you can put some breakpoints into the code to trace the process flow). If everything was set up correctly, you should receive some JSON in the response body that looks similar to the below:

Issuing and authenticating JWT tokens in ASP.NET Core WebAPI – Part II_第2张图片
Paste_Image.png

As you can see, the token expires in 5 min (300 seconds), so you need to move fast! (OK, not really, you can always just send another request, or even change the JwtIssuerOptions.ValidFor setting and recompile(重新编译), so don’t stress)

Copy the token (everything between the “”s for access_token) and create another request in Postman, but this time a GET. Provide the relevant request endpoint (URL) which, if you are using the sample application, is http://localhost:1783/api/test and, under the Headers tab (not Authorization!) add a key/value pair where the key is Authorization (NB! Take note of the American spelling!) and the value is *‘Bearer blahblahblahyourtokencontenthereblahblahblah’. *In other words, you need to provide, as key, the word *Bearer *followed by a single white space, followed by the content of the access_token value you copied above response above (excluding the “”s).

Issuing and authenticating JWT tokens in ASP.NET Core WebAPI – Part II_第3张图片
Paste_Image.png

在截图中,令牌被截断,但它看起来是这样的:

注意:每次您请求一个令牌时,这个值将明显不同,所以请不要使用它,并期望它工作,您必须使用令牌服务器为您提供的令牌!

如果所有的设置都正确设置,您应该收到如下响应(请查看正文)

Issuing and authenticating JWT tokens in ASP.NET Core WebAPI – Part II_第4张图片
Paste_Image.png

Access Denied

OK, so this is all nice and well, the user we expected to have access to that method, had access to that method, but now we also need to confirm that users who do not have the necessary claim credentials are denied access.

Following pretty much the exact same steps as above, set up a POST method for our unauthorised user (note that this user is authenticated, i.e. a valid user, but unauthorised, in other words, although the user is a legitimate user, he/she does not have permission to access the method under test).用户是经过了身份验证的。

我们为这个设置的用户是NotMickeyMouse(在JwtController中再次引用GetClaimsIdentity)

Issuing and authenticating JWT tokens in ASP.NET Core WebAPI – Part II_第5张图片
Paste_Image.png

Once again, copy the bearer token into the Authorization header for a GET request (you can use the exact same GET as before and simply replace the Bearer with the one you get back from NotMickeyMouse). This time, however, you will notice that access is denied.

Issuing and authenticating JWT tokens in ASP.NET Core WebAPI – Part II_第6张图片
Paste_Image.png

这就是ASP.NET的身份中间件,通过基于声明的授权策略来处理基于JWT的访问控制。

In Closing(在结束前)
I recognise that the above could be a touch confusing if you have never worked with Postman or don’t fully understand how the HTTP requests are set up, so please do not hesitate to ask in the comments below if anything is unclear. I will do my best to shed further light on any issues you might encounter.

Cheers!

你可能感兴趣的:(Issuing and authenticating JWT tokens in ASP.NET Core WebAPI – Part II)