asp.net 使用JwtBearer的Ocelot身份验证始终返回401未授权

arknldoa  于 2022-12-30  发布在  .NET
关注(0)|答案(1)|浏览(347)

我们已经构建了一个微服务应用程序,它由3个主要服务组成。我们需要一个Api网关用于路由,主要用于身份验证和授权目的,因为3个服务中的2个需要经过身份验证的用户才能发出请求。路由工作正常,但当我尝试添加身份验证并使用postman测试它时,它无法发送请求,响应为401 Unauthorized。以下是我目前所做的工作:
Ocelot.json

{
"Routes": [
{
  "DownstreamPathTemplate": "/api/courses/{everything}",
  "DownstreamScheme": "https",
  "DownstreamHostAndPorts": [
    {
      "Host": "localhost",
      "Port": 7123
    }
  ],
  "UpstreamPathTemplate": "/api/courses/{everything}",
  "UpstreamHttpMethod": [ "POST", "PUT", "GET", "DELETE" ],
  "AuthenticationOptions": {
    "AuthenticationProviderKey": "Bearer",
    "AllowedScopes": []
  }
},
{
  "DownstreamPathTemplate": "/api/users/{everything}",
  "DownstreamScheme": "http",
  "DownstreamHostAndPorts": [
    {
      "Host": "localhost",
      "Port": 8080
    }
  ],
  "UpstreamPathTemplate": "/api/users/{everything}",
  "UpstreamHttpMethod": [ "POST", "PUT", "GET", "DELETE" ]
},
{
  "DownstreamPathTemplate": "/api/exam/{everything}",
  "DownstreamScheme": "http",
  "DownstreamHostAndPorts": [
    {
      "Host": "localhost",
      "Port": 8888
    }
  ],
  "UpstreamPathTemplate": "/api/exam/{everything}",
  "UpstreamHttpMethod": [ "POST", "PUT", "GET", "DELETE" ],
  "AuthenticationOptions": {
    "AuthenticationProviderKey": "Bearer",
    "AllowedScopes": []
  }
}
],
"GlobalConfiguration": {}
}

我认为生成令牌的服务可能是问题所在,因此我生成了一个在线令牌,但问题仍然相同
一个月一个月九个月一个月九个月九个月一个月九个月九个月九个月九个月一个月
Program.cs文件

using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using  Ocelot.DependencyInjection;
using Ocelot.Middleware;

var builder = WebApplication.CreateBuilder(args);

builder.Configuration.AddJsonFile("Ocelot.dev.json");

builder.Services.AddEndpointsApiExplorer();

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.RequireHttpsMetadata = false;
    options.SaveToken = true;
    options.TokenValidationParameters = new TokenValidationParameters
{
    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("AUTH_SECRET_KEY", EnvironmentVariableTarget.Process)!)),
    ValidateIssuerSigningKey = true,
    ValidateIssuer = false,
    ValidateAudience = false,
};
});

builder.Services.AddOcelot();

var app = builder.Build();

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseOcelot().Wait();

app.UseAuthorization();

app.Run();

IM使用的密钥为"secret"
来自控制台的错误消息:

warn: Ocelot.Authentication.Middleware.AuthenticationMiddleware[0]
      requestId: 0HMIUJ2BDCV3D:00000002, previousRequestId: no previous request id, message: Client has NOT been authenticated for /api/courses/create and pipeline error set. Request for
 authenticated route /api/courses/create by  was unauthenticated
warn: Ocelot.Responder.Middleware.ResponderMiddleware[0]
      requestId: 0HMIUJ2BDCV3D:00000002, previousRequestId: no previous request id, message: Error Code: UnauthenticatedError Message: Request for authenticated route /api/courses/create
 by  was unauthenticated errors found in ResponderMiddleware. Setting error response for request path:/api/courses/create, request method: POST

有人能看出我犯的错误吗?

dbf7pr2w

dbf7pr2w1#

在启动时尝试此操作

var configuration = new OcelotPipelineConfiguration
        {
            AuthenticationMiddleware = async (cpt, est) =>
            {
                await est.Invoke();
            }
        };
        app.UseOcelot(configuration).Wait();

相关问题