Ocelot Easy Tutorial Catalogue
- Ocelot Simple Tutorial (i) what is the Ocelot
- Ocelot Easy Tutorial (ii) Quick Start 1
- Ocelot Easy Tutorial (ii) Quick Start 2
- Ocelot Simple Tutorial (iii) main features and routing details
- Ocelot Simple Tutorial (iv) Request aggregation and service discovery
Ocelot Simple Tutorial (v) Integrated IDENTITYSERVER certification and authorization
Yi Le Zhu
Original address: https://www.cnblogs.com/yilezhu/p/9807125.html
Recently lazy, so separated by N genius to continue to update the fifth Ocelot simple tutorial, this tutorial will be a brief introduction of the official documentation of the content and then in the previous document code based on the demonstration of the example. The goal is to let the small white also follow the steps of the code to run up. Of course, before you start, you have a certain understanding of identityserver and the ability to integrate Identityserver, If you're not integrated with Identityserver, take a look at my Asp.netcorewebapi image upload Interface (ii) Integrated IDENTITYSERVER4 authorized access (attached source) article. There is an example of a step-by-step integration identityserver.
Well, the crap is over, so let's get into today's theme! Ocelot Certification and authorization.
Concept Statement Certification
In order to verify reroutes and then use any claims-based features of Ocelot, such as authorizing or modifying the request with the value in the token. Users must register the authentication service in their Startup.cs as usual, the only difference is that they need to provide a program for each certification registration, for example
public void ConfigureServices(IServiceCollection services){ var authenticationProviderKey = "OcelotKey"; services.AddAuthentication() .AddJwtBearer(authenticationProviderKey, x => { });}
In this example, Ocelotkey is the scheme that this provider has registered. We then map it to the reroute in the configuration, for example
"ReRoutes": [ { "DownstreamPathTemplate": "/api/{everything}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 1001 }, { "Host": "localhost", "Port": 1002 } ], "UpstreamPathTemplate": "/{everything}", "UpstreamHttpMethod": [ "Get", "Post" ], "LoadBalancerOptions": { "Type": "RoundRobin" }, "AuthenticationOptions": { "AuthenticationProviderKey": "OcelotKey", "AllowedScopes": [] } } ]
When Ocelot runs, it looks at Authenticationproviderkey under the Authenticationoptions node in this reroutes and checks if there is an authentication provider registered with the given key. If not, then Ocelot will not start, and if so, reroute will use the provider at execution time.
If reroute is authenticated, Ocelot will call the authentication scheme associated with it when it executes the authentication middleware. If the request fails, the authentication Ocelot returns an HTTP status code of 401, which is an unauthorized state.
JWT Token
If you want to authenticate with a JWT token, possibly from a provider such as OAuth, you can normally register your authentication middleware, for example
public void ConfigureServices(IServiceCollection services){ var authenticationProviderKey = "OcelotKey"; services.AddAuthentication() .AddJwtBearer(authenticationProviderKey, x => { x.Authority = "test"; x.Audience = "test"; }); services.AddOcelot();}
Then map the authentication provider key to the reroute in the configuration, for example
"ReRoutes": [ { "DownstreamPathTemplate": "/api/{everything}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 1001 }, { "Host": "localhost", "Port": 1002 } ], "UpstreamPathTemplate": "/{everything}", "UpstreamHttpMethod": [ "Get", "Post" ], "LoadBalancerOptions": { "Type": "RoundRobin" }, "AuthenticationOptions": { "AuthenticationProviderKey": "OcelotKey", "AllowedScopes": [] } } ]
Identity Server Bearer Tokens authentication
The next leading actor of the day. Identityserver authentication method. In order to use Identityserver to host tokens, follow the conventions of using scenarios (keys) in configureservices to register your identityserver service. If you do not know how to do this, please visit the identityserver documentation. Or check out my Asp.netcorewebapi image upload Interface (ii) Integrated IDENTITYSERVER4 authorized access (attached source) articles.
var authenticationProviderKey = "OcelotKey"; var identityServerOptions = new IdentityServerOptions(); Configuration.Bind("IdentityServerOptions", identityServerOptions); services.AddAuthentication(identityServerOptions.IdentityScheme) .AddIdentityServerAuthentication(authenticationProviderKey, options => { options.RequireHttpsMetadata = false; //是否启用https options.Authority = $"http://{identityServerOptions.ServerIP}:{identityServerOptions.ServerPort}";//配置授权认证的地址 options.ApiName = identityServerOptions.ResourceName; //资源名称,跟认证服务中注册的资源列表名称中的apiResource一致 options.SupportedTokens = SupportedTokens.Both; } ); services.AddOcelot()//注入Ocelot服务 .AddConsul();
Then map the authentication provider key to the reroute in the configuration, for example
"ReRoutes": [ { "DownstreamPathTemplate": "/api/{everything}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 1001 }, { "Host": "localhost", "Port": 1002 } ], "UpstreamPathTemplate": "/{everything}", "UpstreamHttpMethod": [ "Get", "Post" ], "LoadBalancerOptions": { "Type": "RoundRobin" }, "AuthenticationOptions": { "AuthenticationProviderKey": "OcelotKey", "AllowedScopes": [] } } ]
Allowable range of access (allowed Scopes)
If you add a scope to Allowedscopes,ocelot, you get all the user claims for the type range (from the token) and make sure that the user has all the scopes in the list.
This is a way of restricting access to reroute based on scope restrictions. (I didn't use this way, I feel a bit like the concept of identityserver scope)
Example Demo Integrated Identityserver
Create a new Ocelotdemo.auth ASP. NET core Web API project
The project is configured for Identityserver server-side related configurations, which are used in a hard-coded manner for demonstration purposes. Specific configuration can refer to Asp.netcorewebapi image upload Interface (ii) Integrated IDENTITYSERVER4 authorized access (attached source) this article
Add a NuGet package in the Gateway project Ocelotdemo
Install-Package IdentityServer4.AccessTokenValidation
-
Adds identityserver validation to Startup.cs in the Ocelotdemo project as follows:
var Authenticationproviderkey = "Ocelotkey"; var identityserveroptions = new Identityserveroptions (); Configuration.bind ("Identityserveroptions", identityserveroptions); Services. Addauthentication (Identityserveroptions.identityscheme). Addidentityserverauthentication (authenticationproviderkey, options = options. Requirehttpsmetadata = false; Whether to enable HTTPS options. authority = $ "http://{identityserveroptions.serverip}:{identityserveroptions.serverport}";//Configure the address of the authorized authentication O Ptions. Apiname = Identityserveroptions.resourcename; The resource name, which is consistent with the Apiresource in the name of the resource list registered in the authentication service. Supportedtokens = Supportedtokens.both; } ); Services. Addocelot ()//inject Ocelot service. Addconsul ();
In the Ocelot.json that need to be added to the validation reroute, modify the following configuration code:
"ReRoutes": [ { "DownstreamPathTemplate": "/api/{everything}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 1001 }, { "Host": "localhost", "Port": 1002 } ], "UpstreamPathTemplate": "/{everything}", "UpstreamHttpMethod": [ "Get", "Post" ], "LoadBalancerOptions": { "Type": "RoundRobin" }, "AuthenticationOptions": { "AuthenticationProviderKey": "OcelotKey", "AllowedScopes": [] } } ]
Open postman test the code, first visit Http://localhost:1000/values this time the returned result is 401 unauthorized status, as shown in:
Then visit our new Identityserver server above and get token. Configure the corresponding parameters as shown in the Get:
We then use the Access_token we get to access the Ocelot Gateway interface, which is configured as follows:
You can see that the result returns 200 code, and the result is toggled between good and order. Because the Ocelot.json file has a Roundrobin load balancing policy on the route.
Authorized
Ocelot supports claims-based authorization, which runs after authentication. This means that if you have a URL to authorize, you can add the following to the reroute configuration.
"RouteClaimsRequirement": { "UserType": "registered"}
In this example, when the authorization middleware is invoked, Ocelot checks whether the user has a claim type of usertype and whether the value of the claim has been registered. If not, the user will not be authorized and will respond with a 403 forbidden status code.
Of course, this kind of authorization is not applicable in most business scenarios, and it is necessary to rewrite Ocelot middleware in order to implement it. By rewriting the Ocelot middleware you can implement your own authorization logic, if you have limited flow requirements, such as a different throttling policy for each client. For example, there are three client a,b,c. Access the same URL, but we want to control a, can only access 10 times per minute, B can access 20 times per minute, and C does not allow access. There is no relevant implementation for this scenario Ocelot. But we can implement it by rewriting the Ocelot middleware. As space is limited, no introduction is made today. But I will take the time to carry out the relevant implementation, and share to everyone.
Source
The source code for this blog post has been uploaded to GitHub. Can be used for reference. Https://github.com/yilezhu/OcelotDemo
Summarize
This article introduces briefly how Ocelot integrates the authentication authorization, then through the example carries on the Identityserver integration demonstration, hoped can have the certain reference function to everybody. Of course, it is also mentioned that dealing with complex authorizations and limiting the need to rewrite the Ocelot middleware itself is an implementation. How to realize it, I will share it to you as soon as possible. Similarly, by rewriting the Ocelot middleware we can also store Ocelot.json configuration information in a database and cache it in Redis! Finally, thank you for reading!
Ocelot Simple Tutorial (v) Integrated IDENTITYSERVER certification and authorization