Atualmente, estudando Ocelot e microsserviços com .NET 8 No momento, estou com dificuldades em proteger as rotas configuradas no Ocelot com um microsserviço de autenticação (Identity). A ideia no geral, é primeiramente o usuário se autenticar na rota de autenticação e retornar um token Bearer do Identity. Desse token, o usuário poderá acessar as outras rotas configuradas no Ocelot, segue o meu apiGateway.json:
{
"GlobalConfiguration": {
"BaseUrl": "https://localhost:7097"
},
"Routes": [
{
"DownstreamPathTemplate": "/orders/{everything}",
"DownStreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 7047
}
],
"UpstreamPathTemplate": "/gateway/orderservices/{everything}",
"UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PATCH" ],
"AuthenticationOptions": {
"AuthenticationProviderKey": "IdentityApiKey",
"AllowedScopes": []
}
},
{
"DownstreamPathTemplate": "/identity/{everything}",
"DownStreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 7112
}
],
"UpstreamPathTemplate": "/gateway/identity/{everything}",
"UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PATCH" ]
}
]
}
Note que a rota /gateway/orderservices/{everything} está configurada a Authenticação. No meu Program.CS do Ocelot está configurado assim:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
var authenticationProviderKey = "IdentityApiKey";
builder.Configuration.AddJsonFile("apiGateway.json", optional: false, reloadOnChange: true);
builder.Services.AddAuthentication(s =>
{
s.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
s.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(authenticationProviderKey, x =>
{
x.SaveToken = true;
x.RequireHttpsMetadata = false;
x.Authority = "https://localhost:7112";
x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateAudience = false,
ValidateIssuer = false,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authenticationProviderKey))
};
});
builder.Services.AddControllers();
builder.Services.AddOcelot();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.UseOcelot().Wait();
app.Run();
no qual x.Authority = "https://localhost:7112" é onde está localizado o meu servidor de autenticação.
A rota /gateway/orderservices/{everything} está protegida, retornando 401 caso o token seja inválido, o problema é que mesmo que eu coloque um token valido, ainda continua retornando 401 (unauthorized) Será que esqueci de configurar algo?
Segue o Program.cs do Identity:
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using TesteMicroServiços.Context;
var builder = WebApplication.CreateBuilder(args);
string connection = builder.Configuration.GetConnectionString("Database");
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddAuthorization();
builder.Services.AddEntityFrameworkSqlServer().AddDbContext<SqlServerContext>(o => o.UseSqlServer(connection));
builder.Services.AddIdentityApiEndpoints<IdentityUser>().AddEntityFrameworkStores<SqlServerContext>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapGroup("/identity").MapIdentityApi<IdentityUser>();
app.Run();