爲了驗證ReRoutes並隨後使用Ocelot的任何基於聲明的功能,如受權或使用令牌中的值修改請求。 用戶必須像往常同樣在他們的Startup.cs中註冊認證服務,但他們給每一個註冊提供了一個方案(認證提供商密鑰),例如html
public void ConfigureServices(IServiceCollection services) { var authenticationProviderKey = "TestKey"; services.AddAuthentication() .AddJwtBearer(authenticationProviderKey, x => { }); }
在此示例中,TestKey是此提供程序已註冊的方案。 而後,咱們將其映射到配置中的ReRoute,例如api
"ReRoutes": [{ "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 51876, } ], "DownstreamPathTemplate": "/", "UpstreamPathTemplate": "/", "UpstreamHttpMethod": ["Post"], "ReRouteIsCaseSensitive": false, "DownstreamScheme": "http", "AuthenticationOptions": { "AuthenticationProviderKey": "TestKey", "AllowedScopes": [] } }]
當Ocelot運行時,它會查看此ReRoutes的AuthenticationOptions.AuthenticationProviderKey並檢查是否存在給定密鑰註冊的身份驗證提供程序。 若是沒有,那麼Ocelot不會啓動,若是有的話ReRoute將在執行時使用該提供者。ide
若是ReRoute配置了認證,Ocelot在執行認證中間件時將調用與其相關的任何驗證方案。 若是請求認證失敗,Ocelot返回http狀態碼401。code
若是您想使用JWT令牌進行身份驗證,例如Auth0等提供商,您能夠使用正常的方式註冊你的身份驗證中間件。server
public void ConfigureServices(IServiceCollection services) { var authenticationProviderKey = "TestKey"; services.AddAuthentication() .AddJwtBearer(authenticationProviderKey, x => { x.Authority = "test"; x.Audience = "test"; }); services.AddOcelot(); }
而後將身份驗證提供程序密鑰映射到配置中的ReRoute,例如jwt
"ReRoutes": [{ "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 51876, } ], "DownstreamPathTemplate": "/", "UpstreamPathTemplate": "/", "UpstreamHttpMethod": ["Post"], "ReRouteIsCaseSensitive": false, "DownstreamScheme": "http", "AuthenticationOptions": { "AuthenticationProviderKey": "TestKey", "AllowedScopes": [] } }]
爲了使用IdentityServer承載令牌,請按照慣例在ConfigureServices 中使用方案(密鑰)註冊您的IdentityServer服務。 若是您不明白如何操做,請訪問IdentityServer文檔。htm
public void ConfigureServices(IServiceCollection services) { var authenticationProviderKey = "TestKey"; var options = o => { o.Authority = "https://whereyouridentityserverlives.com"; o.ApiName = "api"; o.SupportedTokens = SupportedTokens.Both; o.ApiSecret = "secret"; }; services.AddAuthentication() .AddIdentityServerAuthentication(authenticationProviderKey, options); services.AddOcelot(); }
而後將身份驗證提供程序密鑰映射到配置中的ReRoute,例如中間件
"ReRoutes": [{ "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 51876, } ], "DownstreamPathTemplate": "/", "UpstreamPathTemplate": "/", "UpstreamHttpMethod": ["Post"], "ReRouteIsCaseSensitive": false, "DownstreamScheme": "http", "AuthenticationOptions": { "AuthenticationProviderKey": "TestKey", "AllowedScopes": [] } }]
若是將範圍添加到AllowedScopes,Ocelot將得到類型範圍的全部用戶聲明(從令牌中),並確保用戶具備列表中的全部範圍。blog
這是一種基於範圍限制對ReRoute訪問的方式。文檔