Ошибка носителя. Токен недействителен. Возможна проблема с настройкой docker-compose?C#

Место общения программистов C#
Ответить
Anonymous
 Ошибка носителя. Токен недействителен. Возможна проблема с настройкой docker-compose?

Сообщение Anonymous »

Я видел этот вопрос раньше, но ни один из ответов не решил мою проблему и не помог мне понять, в чем на самом деле проблема.
Поэтому я был бы благодарен за любую помощь. Как упоминалось в заголовке, при попытке достичь авторизованной конечной точки я получаю следующую ошибку:

www-authenticate: Bearer error="invalid_token", error_description="Издатель BookyWooks недействителен".

Я считаю, что моя проблема связана с докером, поэтому я покажу свои файлы, созданные докером, и моя настройка кода:
Сначала мой docker-compose.override.yml:
bookywooks.catalogue.api:
container_name: bookywooks.catalogue.api
environment:
- ASPNETCORE_ENVIRONMENT=Development
- "ConnectionStrings__Database=Server=postgresdb;Database=CatalogueDb;User Id=admin;Password=admin1234;"
- IdentityServerURL=http://bookywooks.identityserver
- RabbitMQConfiguration__Config__HostName=${BOOKYWOOKS_RABBITMQ_HOSTNAME:-rabbitmq}
- RabbitMQConfiguration__Config__UserName=${BOOKYWOOKS_RABBITMQ_USERNAME:-guest}
- RabbitMQConfiguration__Config__Password=${BOOKYWOOKS_RABBITMQ_PASSWORD:-guest}
- "ElasticConfiguration:Uri=http://elasticsearch:9200"
- Jaeger__Protocol=http
- Jaeger__Port=4317
- Jaeger__Host=jaeger
ports:
- "5007:8080"
- "5009:8081"
volumes:
- ${APPDATA}/Microsoft/UserSecrets:/home/app/.microsoft/usersecrets:ro
- ${APPDATA}/ASP.NET/Https:/home/app/.aspnet/https:ro

bookywooks.identityserver:
container_name: bookywooks.identityserver
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_HTTP_PORTS=8080
- ASPNETCORE_HTTPS_PORTS=8081
- "ConnectionStrings__DefaultConnection=Server=identityserverdb;Database=IdentityServerDb;User=sa;Password=Your_password123;MultipleActiveResultSets=true;TrustServerCertificate=true;"
ports:
- "5011:8080"
- "5015:8081"
volumes:
- ${APPDATA}/Microsoft/UserSecrets:/home/app/.microsoft/usersecrets:ro
- ${APPDATA}/ASP.NET/Https:/home/app/.aspnet/https:ro

networks:
booky_wooks_network:
external: true

Затем мой docker-compose.yml:
bookywooks.catalogue.api:
image: ${DOCKER_REGISTRY-}bookywookscatalogueapi
build:
context: .
dockerfile: BookyWooks.Catalogue.Api/Dockerfile
depends_on:
- postgresdb
- rabbitmq
- jaeger
# - otel-collector
networks:
- booky_wooks_network

identityserverdb:
container_name: booky_wooks_identityserverdb
image: "mcr.microsoft.com/mssql/server:2022-latest"
environment:
- "SA_PASSWORD=Your_password123"
- "ACCEPT_EULA=Y"
restart: always
ports:
- "5435:1433"
networks:
- booky_wooks_network

bookywooks.identityserver:
image: ${DOCKER_REGISTRY-}bookywooksidentityserver
build:
context: .
dockerfile: BookyWooks.IdentityServer/Dockerfile
networks:
- booky_wooks_network

networks:
booky_wooks_network:
external: true

Вот моя настройка IdentityServer:
internal static class HostingExtensions
{
public static WebApplication ConfigureServices(this WebApplicationBuilder builder)
{
builder.Services.AddRazorPages();

builder.Services.AddDbContext(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddIdentity()
.AddEntityFrameworkStores()
.AddDefaultTokenProviders();

builder.Services
.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;

// see https://docs.duendesoftware.com/identit ... resources/
options.EmitStaticAudienceClaim = true;
options.IssuerUri = "BookyWooks";
})
.AddInMemoryIdentityResources(Config.IdentityResources)
.AddInMemoryApiScopes(Config.ApiScopes)
.AddInMemoryClients(Config.Clients)
.AddAspNetIdentity();

builder.Services.AddAuthentication()
.AddGoogle(options =>
{
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;

// register your IdentityServer with Google at https://console.developers.google.com
// enable the Google+ API
// set the redirect URI to https://localhost:5001/signin-google
options.ClientId = "copy client ID from Google here";
options.ClientSecret = "copy client secret from Google here";
});

return builder.Build();
}

public static WebApplication ConfigurePipeline(this WebApplication app)
{
app.UseSerilogRequestLogging();

if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseStaticFiles();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthorization();

app.MapRazorPages()
.RequireAuthorization();

return app;
}
}

Вот мои настройки BookCatalogue:
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog(SeriLogger.Configure);
// Add services to the container.
var assembly = typeof(Program).Assembly;
builder.Services.AddMediatR(config =>
{
config.RegisterServicesFromAssembly(assembly);
});
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();

builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Book Catalogue Microservice", Version = "v1" });
// To Enable authorization using Swagger (JWT)
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "Enter 'Bearer' [space] and then your valid token in the text input below.\r\n\r\nExample: \"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9\"",
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, Array.Empty() } });

var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});

builder.Services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
var identityServerUrl = builder.Configuration["IdentityServerURL"];
options.Authority = identityServerUrl;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false
};
});
builder.Services.AddAuthorization();
//builder.Services.AddMarten(opts =>
//{
// opts.Connection(builder.Configuration.GetConnectionString("Database")!);
//}).UseLightweightSessions();
builder.Services.AddDbContext(x =>
{
x.UseNpgsql(builder.Configuration.GetConnectionString("Database")!, opt =>
{
var x = builder.Configuration.GetConnectionString("Database");
opt.EnableRetryOnFailure(5);
});
});
builder.Services.AddScoped();
//if (builder.Environment.IsDevelopment())
//builder.Services.InitializeMartenWith();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddMessageBroker(builder.Configuration, Assembly.GetExecutingAssembly(), false);
builder.Services.AddOpenTelemetryTracing(builder.Configuration);
builder.Services.AddOpenTelemetryMetrics(builder.Configuration);
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
//app.UseSwagger();
//app.UseSwaggerUI();
await app.InitialiseDatabaseAsync();
}
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Book Catalogue Microservice"));
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");

app.UseOpenTelemetryPrometheusScrapingEndpoint();
app.MapControllers();
app.Run();

Вот мой контроллер BookCatalogue:
[ApiController]
[Route("api/[controller]")]
public class BookCatalogueController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

private readonly ILogger _logger;

public BookCatalogueController(ILogger logger)
{
_logger = logger;
}

[Authorize]
[HttpGet("products")]
public IEnumerable Get()
{
return Enumerable.Range(1, 5).Select(index => new Product
{
Id = new Guid("1e9c1a7e-1d9b-4c0e-8a15-5e12b5f5ad34"),
Name = "To Kill a Mockingbird",
Description = "A novel about the serious issues of rape and racial inequality, told through the eyes of a young girl.",
ImageFile = "to-kill-a-mockingbird.png",
Price = 10.99M,
Category = new List { "Fiction" },
Quantity = 10
}).ToArray();
}

[HttpGet("products/test")]
public IEnumerable GetProductsTest()
{
return Enumerable.Range(1, 5).Select(index => new Product
{
Id = new Guid("1e9c1a7e-1d9b-4c0e-8a15-5e12b5f5ad34"),
Name = "To Kill a Mockingbird",
Description = "A novel about the serious issues of rape and racial inequality, told through the eyes of a young girl.",
ImageFile = "to-kill-a-mockingbird.png",
Price = 10.99M,
Category = new List { "Fiction" },
Quantity = 10
}).ToArray();
}
}
```csharp

Here is how I generate a token:
[![enter image description here][1]][1]

Here is that token enccoded in jwt.io:
[![enter image description here][2]][2]

Here is me using swagger to authorize:
[![enter image description here][3]][3]

And here is the error:
[![enter image description here][4]][4]

This question was asked here:
[Stackoverflow bearer error][5]

[1]: https://i.sstatic.net/AJLWPd58.png
[2]: https://i.sstatic.net/3LAs4QlD.png
[3]: https://i.sstatic.net/xVvEJnli.png
[4]: https://i.sstatic.net/fzhBz486.png
[5]: https://stackoverflow.com/questions/603 ... is-invalid
However I do not believe it was actually resolved and if so I have failed to understand the answer. Can anyone please help?


Подробнее здесь: https://stackoverflow.com/questions/786 ... etup-issue
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»