通过CORS进行身份验证不会设置HttpContext.User

时间:2019-01-21 17:00:45

标签: javascript asp.net-core fetch asp.net-core-2.2

当前,我面临以下问题: 我正在使用CORS通过JavaScript提取API对我的ASP.NET-CORE 2.2 WebAPI进行身份验证。 为此,我使用以下代码:

const resp = await fetch(url, {
    method: 'POST',
    credentials: 'include',
    mode: 'cors'
});

url包含指向我的登录API调用的链接。

登录呼叫如下所示:

[HttpPost]
[Route("Login/{username}/{password}")]
[AllowAnonymous]
public async Task<IActionResult> Login(string username, string password)
{
    var theUser = await userManager.FindByNameAsync(username);
    if (theUser == null)
    {
        return BadRequest(userNotExistingMessage);
    }
    var result = await signInManager.PasswordSignInAsync(theUser, password, false, false);
    if (result.Succeeded)
    {
       return Ok(loginMessage);
    } else
    {
       return BadRequest(wrongPasswordMessage);
    }
}

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAll", builder =>
        {
            builder
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials();
        });
    });

    // Authentication
    services.AddAuthentication(sharedOptions =>
    {
       sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    })
    .AddCookie(
    CookieAuthenticationDefaults.AuthenticationScheme,
    options =>
    {
        options.LoginPath = "/api/account/Login";
        options.Cookie.Name = "AUTHCOOKIE";
        options.ExpireTimeSpan = new TimeSpan(365, 0, 0, 0);
        options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
        options.Cookie.SameSite = SameSiteMode.None;
    });

    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => false;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    // DB
    services.AddDbContext<ApplicationDbContext>(options => options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));
    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddDefaultTokenProviders()
        .AddEntityFrameworkStores<ApplicationDbContext>();

    // Sessions
    services.AddDistributedMemoryCache();
    services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromMinutes(20);
        options.Cookie.SameSite = SameSiteMode.None;
        options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
        options.Cookie.IsEssential = true;
    });

    services.AddMvc()
        .AddJsonOptions(options =>
        {
            options.SerializerSettings.Formatting = Formatting.Indented;
        }
    );
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors("AllowAll");

    // Authorization
    var cookiePolicyOptions = new CookiePolicyOptions
    {
        Secure = CookieSecurePolicy.SameAsRequest,
        MinimumSameSitePolicy = SameSiteMode.None
    };
    app.UseCookiePolicy(cookiePolicyOptions);

    // Session
    app.UseSession();
    app.Use((httpContext, nextMiddleware) =>
    {
        httpContext.Session.SetString(SessionVariables.CID, httpContext.Session.Id);
        return nextMiddleware();
    });

    app.UseMvc();
}

当我添加Swagger并访问Login时,一切正常: 使用PasswordSignInAsync()登录用户后,将设置HttpContext.User并可以在进一步使用API​​的过程中对其进行访问。 但是,当我尝试使用前面显示的访存从javascript访问我的API时,似乎未设置HttpContext.User。这就是为什么我无法访问其必须具有的任何属性。

我尝试了艰苦的工作来完成这项工作,但是没有任何效果。那让我发疯。那里有人可以帮助我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

安全设置可能不允许JavaScript访问cookie。

您可以尝试查看以下内容(从HttpOnly到None)是否有效:

var cookiePolicyOptions = new CookiePolicyOptions
{
 Secure = CookieSecurePolicy.SameAsRequest,
 MinimumSameSitePolicy = SameSiteMode.None,
 //Try setting this
 HttpOnly = Microsoft.AspNetCore.CookiePolicy.HttpOnlyPolicy.None
};

和/或(options.Cookie.HttpOnly = false):

 services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
    .AddCookie(
    CookieAuthenticationDefaults.AuthenticationScheme,
    options =>
    {
        options.LoginPath = "/api/account/Login";
        options.Cookie.Name = "AUTHCOOKIE";
        options.ExpireTimeSpan = new TimeSpan(365, 0, 0, 0);
        options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
        options.Cookie.SameSite = SameSiteMode.None;
        options.Cookie.HttpOnly = false; // Try this
    });