登录主体但 User.Identity.IsAuthenticated 为 False 且 HttpContext.AuthenticateAsync 为 False

问题描述

我已手动登录到 .NET Core 3 Web API 应用程序,如下面的控制器操作所示。无论我尝试什么,我似乎都无法让 .NET 框架识别出应用程序用户已登录。我正在 Visual Studio 中进行本地测试,但是当我在服务器上进行测试时也会反映这种行为。为什么我在 HttpContext.SignInAsync 方法中创建和使用的主体没有被发送到中间件(至少看起来好像不是)?

注意:我似乎有一些帖子,用户说您必须登录然后向服务器发出另一个请求才能使新主体生效。我试过了,但结果是一样的。

Startup.cs

public void ConfigureServices(IServiceCollection services)
{

//........

    services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = DefaultAuthenticationTypes.ApplicationCookie;
            })
    .AddCookie(DefaultAuthenticationTypes.ApplicationCookie,options =>
        {
            // true by default   
            options.SlidingExpiration = true;
            // 14 days by default
            options.ExpireTimeSpan = TimeSpan.FromMinutes(120);
            options.Cookie.IsEssential = true;
            options.Cookie.HttpOnly = true;
            options.Cookie.SameSite = SameSiteMode.None;

            options.LoginPath = "/Login";
            options.LogoutPath = "/Logout";
        });
        services.AddAuthorization();

//........

}        

public void Configure(IApplicationBuilder app)
{

//........

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseSession();
        app.UseCors();

//........

}

控制器动作:

ClaimsIdentity userIdentity = 
    new ClaimsIdentity(jwtSecurityToken.Claims,DefaultAuthenticationTypes.ApplicationCookie);
ClaimsPrincipal principal = 
    new ClaimsPrincipal(userIdentity);
await HttpContext.SignInAsync(DefaultAuthenticationTypes.ApplicationCookie,principal,new AuthenticationProperties
    {
        IsPersistent = true,ExpiresUtc = DateTime.UtcNow.AddDays(7)
    });

AuthenticateResult authenticateResult = 
    await httpContext.AuthenticateAsync(DefaultAuthenticationTypes.ApplicationCookie);
//This always returns false!!!

User.Identity.IsAuthenticated
//This always returns false!!!

解决方法

我讨厌这样做,但这段代码确实有效。如果您直接通过浏览器点击此代码,该代码将按预期登录,并且一切按预期运行。

我试图做的是通过 Vue.js 前端应用程序在后端使用 .NET Core 3 Web API 2 应用程序使其工作。出于某种原因,Vue 应用程序无法登录后端应用程序。当我在 Vue 首页上点击 API 操作以通过 Vue 代码登录时,.NET 代码登录时没有错误,但在来自 VUE 的任何其他调用中应用程序,.NET 应用程序表示用户未经授权。我怀疑 cookie 的存储方式和 cookie 的数据隐私存在问题。

在此问题的上下文中,此代码按预期工作。谢谢。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...