最近在使用Ocelot网关,刚开始了解,网上的资料很多,但是使用时还是碰到很多问题,可能和版本有关,比如老的路由配置是ReRoutes,而新版是Routes。关于网关中的统一认证选项AuthenticationOptions的正确设置方法,我根据网上的资料设置时,总是401错误,无法通过认证,踩了很多坑,经过两天的研究,终于找到了正确的可行的方法。
1、假设有Webapi,地址为 http://localhost:6001/weatherforecast,在网关中的 ocelost.json中配置如下:
{
"Routes": [
{
"DownstreamPathTemplate": "/weatherforecast",
"UpstreamPathTemplate": "/weatherforecast",
"UpstreamHttpMethod": [ "GET", "POST", "PULL", "DELETE" ],
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 6001
}
]
,
"AuthenticationOptions": {
"AuthenticationProviderKey": "demoapi",
"AllowedScopes": [ ]
}
}
],
"GlobalConfiguration": {}
}
Webapi中是否设置鉴权声明不重要,这里以网关统一认证来说明,Webapi中不加入任何鉴权代码。
AuthenticationOptions 就是网关统一认证的参数,这里的 AuthenticationProviderKey可自定义,对应的路由可各自独立设置。
2、在网关的Startup.cs中ConfigServices方法加入如下代码:
public void ConfigureServices(IServiceCollection services)
{
services
.AddAuthentication("Bearer")
.AddJwtBearer("demoapi", options =>
{
options.Authority = "http://identityserver4";
options.RequireHttpsMetadata = false;
options.Audience = "ApiResource";
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters(){
ValidAudiences = new[]
{
"http://identityserver4/resources",
"ApiResource"
},
};
})
;
services.AddOcelot();
services.AddControllers();
}
在网上有很多的文章在说明ConfigureServices里的代码时,都没有表达清楚,而且对 AddJwtBearer和 AddIdentityServerAuthentication两个方法使用混淆不清,反正我看的是一头雾水,到底是用AddJwtBearer还是 AddIdentityServerAuthentication弄不清楚。实际上,对于同一个AuthenticationProviderKey,是不能同时使用这两个方法的,正确的用法应该是AddJwtBearer。
另外,options.TokenValidationParamers参数是必须设置的,否则验证时就会抛出异常,ValidAudiences参数为字符串数组,其中第一个参数应为IdentityServer4的服务器加/resources的接口地址,拼成的地址形式类似 http://identityserver4/resources,第二个参数为 ApiScope名称 ,如"ApiResource"。
3、基于Ocelot网关的程序,设置好以上的选项,编译执行,就可以在网关侧统一认证了。