Настройка YARP (appsettings.json)
Код: Выделить всё
"ApiGateway": {
"Routes": {
"main-route": {
"ClusterId": "mainCluster",
"Match": {
"Path": "/main/{**catch-all}"
},
"AuthorizationPolicy": "Authenticated"
},
"auth-route": {
"ClusterId": "authCluster",
"Match": {
"Path": "/auth/{**catch-all}"
}
}
},
"Clusters": {
"mainCluster": {
"Destinations": {
"mainDestination": {
"Address": "http://localhost:5102/"
}
}
},
"authCluster": {
"Destinations": {
"authDestination": {
"Address": "http://localhost:5101/"
}
}
}
}
}
Код: Выделить всё
public static IServiceCollection AddJwt(this IServiceCollection services, IConfiguration configuration)
{
var issuer = Environment.GetEnvironmentVariable("JWT_ISSUER") ??
throw new InvalidOperationException("Cannot find JWT ISSUER");
var secret = Environment.GetEnvironmentVariable("JWT_SECRET") ??
throw new InvalidOperationException("Cannot find JWT SECRET");
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = issuer,
ValidAudience = issuer,
SignatureValidator = (token, parameters) =>
{
var jwt = new JwtSecurityToken(token);
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
if (signingCredentials.Key is not SymmetricSecurityKey symmetricSecurityKey)
throw new InvalidOperationException("Token Signature validation failed.");
var encodedData = $"{jwt.EncodedHeader}.{jwt.EncodedPayload}";
var compiledSignature = Encode(encodedData, symmetricSecurityKey.Key);
if (compiledSignature == jwt.RawSignature)
return jwt;
throw new InvalidOperationException("Token Signature validation failed.");
},
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret)),
ClockSkew = TimeSpan.Zero
};
});
return services;
}
private static string Encode(string encodedData, byte[] key)
{
HMACSHA256 myHmacsha256 = new HMACSHA256(key);
byte[] bytes = Encoding.UTF8.GetBytes(encodedData);
using MemoryStream ms = new MemoryStream(bytes);
byte[] hash = myHmacsha256.ComputeHash(ms);
return Base64UrlEncoder.Encode(hash);
}
Код: Выделить всё
var allowedSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy(allowedSpecificOrigins, policy =>
{
policy.WithOrigins("http://localhost:4200",
"https://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
// Add services to the container.
builder.Services.AddReverseProxy()
.LoadFromConfig(builder.Configuration.GetSection("ApiGateway"));
builder.Services.AddJwt(builder.Configuration);
builder.Services.AddAuthorizationBuilder()
.AddPolicy("Authenticated", policy => policy.RequireAuthenticatedUser());
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseCors(allowedSpecificOrigins);
app.UseAuthentication();
app.UseAuthorization();
app.MapReverseProxy();
app.Run();
Я на самом деле сначала попробовал это с Ocelot и перешел на YARP, когда мне не удалось заставить его работать, и все еще безуспешно. Кто-нибудь, укажите мне, что мне не хватает, пожалуйста. Прошло уже 3 дня.
Подробнее здесь: https://stackoverflow.com/questions/790 ... using-yarp