我有一个 API 网关,在本例中称为 Gateway.Api。在Startup
课堂上,我有以下内容:
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddOcelot(Configuration);
services.AddMvc();
var appSettingSection = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingSection);
var appSettings = appSettingSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseOcelot().Wait();
app.UseMvc();
}
如您所见,它定义了身份验证方案。
使用Ocelot
我的以下配置文件Gateway.Api
:
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/api/customer",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 50366
}
],
"UpstreamPathTemplate": "/api/customer",
"UpstreamHttpMethod": [ "Get" ],
"AuthenticationOptions": {
"AuthenticationProviderKey": "Bearer",
"AllowedScopes": []
}
},
{
"DownstreamPathTemplate": "/api/user/authenticate",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 50353
}
],
"UpstreamPathTemplate": "/api/user/authenticate",
"UpstreamHttpMethod": [ "Post" ]
}
],
"GlobalConfiguration": {
"UseServiceDiscovery": false
}
}
当我尝试在没有令牌的情况下访问http://localhost:50333/api/customer(Gateway.Api 的端口为 50333)时,我收到 401 响应,证明配置文件和身份验证都有效。
除了客户微服务,我还有一个身份微服务,它允许用户使用有效的用户名和密码进行身份验证,然后发出一个令牌。然后使用此令牌调用客户服务,我得到一个成功的响应(200 OK)。
现在由于某种原因,如果我直接访问客户服务而不使用网关(所以http://localhost:50366/api/customer)我能够在没有令牌的情况下获得成功的响应。
下面是客户微服务:
[Route("api/[controller]")]
public class CustomerController : Controller
{
[HttpGet]
public IEnumerable<string> Get()
{
var customers = new string[] {
"test",
"test"
};
return customers;
}
}
这是否意味着我必须为每个微服务Startup
类添加一个身份验证方案?如果是这样,这不是矫枉过正吗?
我所做的尝试是[Authorize]
在 Customer 微服务中的操作上使用一个属性,但这会引发一个异常,即它们不是默认的身份验证方案。