Configure .net Core 9 с OpenIddict в DockerC#

Место общения программистов C#
Ответить
Anonymous
 Configure .net Core 9 с OpenIddict в Docker

Сообщение Anonymous »

Я контейнерирую API .NET Core 9 с OpenIddict и запускаю его в Docker. Следуя рекомендациям OpenIddict, я создал два сертификата RSA (отдельно от сертификата HTTPS): один для шифрования и один для подписания. Эти сертификаты были сгенерированы и самоподвегивались локально с использованием API Core Core .NET API (см.: OpenIddict Docs
). Ниже моя программа.cs. < /P>

Код: Выделить всё

builder.Services.AddOpenIddict()
.AddCore(opt => {
opt.UseEntityFrameworkCore()
.UseDbContext < ApplicationDbContext > ();
})
.AddServer(opt => {
opt.SetTokenEndpointUris("connect/token");
opt.AllowClientCredentialsFlow().AllowRefreshTokenFlow();
opt.AllowPasswordFlow().AllowRefreshTokenFlow();

opt.AcceptAnonymousClients();

if (builder.Environment.IsProduction()) {
try {

var signingCertPath = config["OpenIddict:Certificates:Signing:Path"];
var signingCertPassword = config["OpenIddict:Certificates:Signing:Password"];
var encryptionCertPath = config["OpenIddict:Certificates:Encryption:Path"];
var encryptionCertPassword = config["OpenIddict:Certificates:Encryption:Password"];

bool certificatesLoaded = false;

if (!string.IsNullOrWhiteSpace(signingCertPath)) {
if (File.Exists(signingCertPath)) {
Log.Information("Loading signing certificate from: {Path}", signingCertPath);
opt.AddSigningCertificate(new X509Certificate2(signingCertPath, signingCertPassword));
certificatesLoaded = true;
} else {
Log.Warning("Signing certificate file not found: {Path}", signingCertPath);
}
}

if (!string.IsNullOrWhiteSpace(encryptionCertPath)) {
if (File.Exists(encryptionCertPath)) {
Log.Information("Loading encryption certificate from: {Path}", encryptionCertPath);
opt.AddEncryptionCertificate(new X509Certificate2(encryptionCertPath, encryptionCertPassword));
} else {
Log.Warning("Encryption certificate file not found: {Path}", encryptionCertPath);
}
}

if (!certificatesLoaded && OperatingSystem.IsWindows()) {
var signingThumbprint = config["OpenIddict:Certificates:Signing:Thumbprint"];
var signingStoreLocation = config["OpenIddict:Certificates:Signing:StoreLocation"];

if (!string.IsNullOrWhiteSpace(signingThumbprint)) {
Log.Information("Loading signing certificate from Windows Certificate Store: {Thumbprint}", signingThumbprint);
opt.AddSigningCertificate(CertificateHelper.GetCertificateByThumbprint(signingThumbprint, signingStoreLocation!));
certificatesLoaded = true;
}
}

if (!certificatesLoaded) {
Log.Warning("No production certificates found, falling back to development certificates");
opt.AddDevelopmentEncryptionCertificate()
.AddDevelopmentSigningCertificate();
}
} catch (Exception ex) {
Log.Error(ex, "Failed to load production certificates, falling back to development certificates");
opt.AddDevelopmentEncryptionCertificate()
.AddDevelopmentSigningCertificate();
}
} else {
// Development certificates for local development
opt.AddDevelopmentEncryptionCertificate()
.AddDevelopmentSigningCertificate();
}

opt.DisableAccessTokenEncryption();
opt.UseAspNetCore()
.EnableTokenEndpointPassthrough()
.EnableAuthorizationEndpointPassthrough();

if (builder.Environment.IsDevelopment()) {
opt.UseAspNetCore().DisableTransportSecurityRequirement();
}
});
dockerfile

Код: Выделить всё

FROM mcr.microsoft.com/dotnet/aspnet:9.0-bookworm-slim AS base
USER root

RUN mkdir -p /app/logs && \
mkdir -p /app/certificates && \
chmod 755 /app/logs && \
chmod 700 /app/certificates

# Create app user if it doesn't exist and set ownership
RUN groupadd -r app && useradd -r -g app app || true
RUN chown -R app:app /app

WORKDIR /app
EXPOSE 8080
EXPOSE 8081

FROM mcr.microsoft.com/dotnet/sdk:9.0-bookworm-slim AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["Rock.Identity.API.csproj", "."]
RUN dotnet restore "./Rock.Identity.API.csproj"
COPY .  .
WORKDIR "/src/."
RUN dotnet build "./Rock.Identity.API.csproj" -c $BUILD_CONFIGURATION -o /app/build

FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./Rock.Identity.API.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false

FROM base AS final
WORKDIR /app

COPY --from=publish /app/publish .

COPY appsettings*.json ./ 2>/dev/null || echo "No additional appsettings files found"

COPY certificates/*.pfx /app/certificates/ 2>/dev/null || echo "No certificates found in build context - using development certificates"

RUN if [ -d "/app/certificates" ] && [ "$(ls -A /app/certificates 2>/dev/null)" ]; then \
chown -R app:app /app/certificates && \
chmod 600 /app/certificates/*.pfx 2>/dev/null || true; \
fi

USER $APP_UID

ENTRYPOINT ["dotnet", "Rock.Identity.API.dll"]
docker-compose.yml

Код: Выделить всё

version: '3.8'

services:
identity-api:
build:
context: .
dockerfile: Dockerfile
ports:
- "3400:8080"   # HTTP
- "3401:8081"   # HTTPS
environment:
- DOTNET_ENVIRONMENT=Docker
volumes:
# Mount logs directory for persistence
- ./logs:/app/logs
# Option 1: Mount certificates from host (if you want to manage them externally)
- ./certificates:/app/certificates:ro
# Option 2: Use Docker secrets (uncomment below and comment above)
# secrets:
#   - signing_cert
#   - encryption_cert
networks:
- identity-network
depends_on:
- postgres
restart: unless-stopped

postgres:
image: postgres:15
environment:
POSTGRES_DB: IdentityDb_Prod
POSTGRES_USER: postgres
POSTGRES_PASSWORD: 12345
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
networks:
- identity-network
restart: unless-stopped

networks:
identity-network:
driver: bridge

volumes:
postgres_data:
в slaunchsettings.json я создал два профиля, такие как,
"Container (Dockerfile)": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "http://localhost:3400/swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"publishAllPorts": true,
"useSSL": false
},
"Container (Dockerfile) - Production": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "https://localhost:3401/swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Production"
},
"publishAllPorts": true,
"useSSL": true
}
< /code>
После выбора производственного профиля я получаю эту ошибку во время выполнения < /p>

system.invalidoperationexception: 'Невозможно настроить конечную точку HTTPS. Чтобы сгенерировать сертификат разработчика
запустить 'dotnet dev-certs https'. Чтобы доверять сертификату
(только для Windows и MacOS) запустить 'Dotnet Dev-Certs https
-доверие'. Для получения дополнительной информации о настройке https см. Https://go.microsoft.com/fwlink/?linkid=848054.'

Я ошибался в настройке Docker или в том, как я использую сертификаты в контейнерах Linux?>

Подробнее здесь: https://stackoverflow.com/questions/797 ... -in-docker
Ответить

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

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

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

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

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