环境:
- window10 x64
- vs2022 企业版 17.0.0
- .NET 6.0
- IdentityServer4.AccessTokenValidation 3.0.1
- Ocelot 17.0.0
Ocelot是在.net core下网关的实现类库,通过Ocelot可以统一管理我们的webapi,不用再代码中调来调去的很多api地址,统一从网关调用就行了。
本文涉及IdentityServer4详见 IdentityServer4的使用说明https://blog.youkuaiyun.com/jccgg/article/details/121264055https://blog.youkuaiyun.com/jccgg/article/details/121264055
第一步:新建一个api 做关网 在nuget里面先引用 ocelot 。
同时也引用下 IdentityServer4.AccessTokenValidation
第二步:在startup类中添加
这里需要添加 :
在ConfigureServices方法中添加
Services.AddOcelot(new ConfigurationBuilder()
.AddJsonFile("configuration.json")
.Build());
Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication("TestKey", options =>
{
//ids4的地址
options.Authority = "http://localhost:19128";
options.RequireHttpsMetadata = false;
options.ApiName = "api";
});
跟
Configure类中添加
await app.UseOcelot();
app.UseAuthentication();
然后在网关的配置文件里面去添加 继承 ids4的配置:
例如: 这里大部分都是ocelot的配置,上游地址配置,下游地址配置
{
"Routes": [
{
"DownstreamPathTemplate": "/api/weather",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 19128
}
],
"UpstreamHttpMethod": [ "Get", "Post" ],
"UpstreamPathTemplate": "/weather",
"AuthenticationOptions": {
"AuthenticationProviderKey": "TestKey",
"AllowScopes": []
}
}
]
}
所以只需要配置这个就可以了。
第三步:调式
不走网关直接访问下游接口:
走网关访问上游接口:
401说明认证不通过,我们需要获取access_token。
访问ids4接口获取access_token:
拿到access_token后,去访问上游接口:
在Type里面选择 Bearer Token 就有一个需要让你输入的地址,输入这串密文。就可以,就可以调用,如果密文为空或者不对,你可以试试,肯定是调不通接口,拿不到你需要的值。
成功请求到了数据。