@savva09
Начинающий .NET-ер

Почему DataProtection при запуске в Docker ломается?

Я захотел использовать TempData в контроллере. В частности потребовалось написать 2 конечные точки: get login и post login, get должен принимать опциональный параметр returnTo и класть его в TempData, а post должен отправить редирект на returnTo после авторизации.

Я сделал AddSession и UseSession как подсказал gpt:
builder.Services.AddSession();
app.UseRouting();

app.UseSession();

app.UseAuthorization();


и у меня посыпался csrf токен:
Exception

2024-10-16 20:53:37 warn: Microsoft.AspNetCore.Mvc.ViewFeatures.CookieTempDataProvider[3]
2024-10-16 20:53:37 The temp data cookie .AspNetCore.Mvc.CookieTempDataProvider could not be loaded.
2024-10-16 20:53:37 System.Security.Cryptography.CryptographicException: The key {f660ab16-e809-4fa7-bb78-d65ef6316790} was not found in the key ring. For more information go to https://aka.ms/aspnet/dataprotectionwarning
2024-10-16 20:53:37 at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status)
2024-10-16 20:53:37 at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData)
2024-10-16 20:53:37 at Microsoft.AspNetCore.Mvc.ViewFeatures.CookieTempDataProvider.LoadTempData(HttpContext context)
2024-10-16 20:53:37 fail: Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery[7]
2024-10-16 20:53:37 An exception was thrown while deserializing the token.
2024-10-16 20:53:37 Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The antiforgery token could not be decrypted.
2024-10-16 20:53:37 ---> System.Security.Cryptography.CryptographicException: The key {f660ab16-e809-4fa7-bb78-d65ef6316790} was not found in the key ring. For more information go to https://aka.ms/aspnet/dataprotectionwarning
2024-10-16 20:53:37 at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status)
2024-10-16 20:53:37 at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData)
2024-10-16 20:53:37 at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken)
2024-10-16 20:53:37 --- End of inner exception stack trace ---
2024-10-16 20:53:37 at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken)
2024-10-16 20:53:37 at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery.GetCookieTokenDoesNotThrow(HttpContext httpContext)


Еще увидел warnы при старте
spoiler
2024-10-16 21:13:53 warn: Microsoft.AspNetCore.DataProtection.Repositories.EphemeralXmlRepository[50]
2024-10-16 21:13:53 Using an in-memory repository. Keys will not be persisted to storage.
2024-10-16 21:13:53 warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[59]
2024-10-16 21:13:53 Neither user profile nor HKLM registry available. Using an ephemeral key repository. Protected data will be unavailable when application exits.
2024-10-16 21:13:53 warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
2024-10-16 21:13:53 No XML encryptor configured. Key {7cca425c-e892-4444-840f-9bc68ca4f3fa} may be persisted to storage in unencrypted form.


Вот и возникает вопрос: что я делаю не так?
При попытке сделать аналогичное действие вне docker контейнера все получается, попробовал 2 раза

Если надо:
Полный program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddSession();

builder.Services.AddControllersWithViews();

builder.Services.AddHttpClient();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseSession();

app.UseAuthorization();

app.MapControllers();

app.Run();

Код контроллера
[Controller]
    [Route("[action]")]
    public class LoginController(HttpClient httpClient) : Controller
    {
        private readonly HttpClient _httpClient = httpClient;

        [HttpGet("/{returnTo?}")]
        public IActionResult Login(string? returnTo)
        {
            if (returnTo != null)
                TempData["returnTo"] = returnTo;
            return View();
        }

        [HttpPost("/")]
        public IActionResult Login()
        {

            if (TempData.TryGetValue("returnTo", out object? value) && value is string str && !string.IsNullOrEmpty(str))
                return RedirectPermanent(str);
            else
                return View();
        }
    }
  • Вопрос задан
  • 346 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы