我一直在尝试设置两个(最终更多).NET Core 2.0 API .

一个将处理身份验证,创建声明并将其存储在cookie中的人 . 理想情况下,其他人应该使用相同的cookie来授予对授权 endpoints 的访问权限 .

然而,我遇到了一些问题,第二个服务没有识别 - 或使用 - 我在auth服务中创建的cookie .

我的Startup.cs文件(对于这两种服务)看起来像这样......

public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.Cookie = new CookieBuilder
                {
                    Name = ".AuthCookie",
                    Domain = "localhost",
                    SecurePolicy = CookieSecurePolicy.SameAsRequest,
                    SameSite = SameSiteMode.Lax,
                    HttpOnly = false
                };

                // Events
                // On redirect to login, return 401
                options.Events.OnRedirectToLogin = (context) =>
                {
                    context.Response.StatusCode = 401;
                    return Task.CompletedTask;
                };

                // On access denied, return 403
                options.Events.OnRedirectToAccessDenied = (context) =>
                {
                    context.Response.StatusCode = 403;
                    return Task.CompletedTask;
                };
            });

        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseAuthentication();

        app.UseMvc();
    }

出于测试目的,我创建了一个用于创建声明的HttpGet调用,因此 endpoints 看起来像这样......

[HttpGet]
    [Route("login")]
    public async Task Login()
    {
        // Generate the list of claims
        // TODO: Generate claims based on data from post
        var claims = new List
        {
            new Claim(ClaimTypes.NameIdentifier, "identifier"),
            new Claim(ClaimTypes.Name, "name")
        };

        // Create the claims identity
        var identity = new ClaimsIdentity(claims, "login");

        // Initialize the principal
        var principal = new ClaimsPrincipal(identity);

        // Sign in using the principal
        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

        // Return the all-clear
        return Ok("Logged in");
    }

总而言之,创建此cookie的服务可以使用它,但其他服务很难看到您应该进行身份验证 .

这两个服务都在docker容器中运行,如果它是相关的,并且可以通过localhost域访问,如下所示: http://localhost:{ServicePort}

由于我一直无法找到任何有用的文档,因此大多数关于cookie共享的文章似乎早于.NET Core 2.0中的当前实现

任何关于我可能做错的提示都将不胜感激 .

解决方案

Evk提供,我必须启用服务AddDataProtection并在两个(或所有)服务可以访问的文件系统上保留它们的密钥 .

services.AddDataProtection()
    .PersistKeysToFileSystem(new DirectoryInfo(@"/appdata"));