【问题标题】:Cookie not generated in browser on ASP.NET Core Web ApplicationCookie 未在 ASP.NET Core Web 应用程序的浏览器中生成
【发布时间】:2020-01-10 09:42:31
【问题描述】:

我有一个应用程序分为 2。后端 asp.net 核心 Web 应用程序在端口 localhost/5001 上运行。在端口 localhost/3000 上运行的前端反应 js 应用程序。两者都配置为在 https 上运行。登录时没有生成cookie,但是登录成功。

这是 Startup.cs 中的 ConfigureService 方法

  public void ConfigureServices(IServiceCollection services)
    {
        var connectionString = _config.GetConnectionString("DefaultConnection");

        services.AddHttpsRedirection(options =>
        {
            options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
            options.HttpsPort = 5001;
        });

        services.AddDbContext<AppDbContext>(options => options.UseSqlServer(connectionString));

        services.AddIdentity<User, IdentityRole>(options =>
        {
            options.Password.RequireDigit = false;
            options.Password.RequireLowercase = false;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = false;
            options.Password.RequiredLength = 6;
        })
            .AddDefaultTokenProviders()
            .AddEntityFrameworkStores<AppDbContext>();

        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        // services.AddSession();
        services.AddSession(opts =>
        {
            opts.Cookie.IsEssential = true; // make the session cookie Essential
        });

        services.AddCors(options =>
        {
            options.AddPolicy(enableCors, builder =>
            {
                builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials();
            });
        });
    }

这是 Startup.cs 中的 Configure 方法

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

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

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

        app.UseCors(enableCors);
        app.UseMvc();
    }

这是后端登录端点

[Route("login")]
    [HttpPost]
    public async Task<IActionResult> Login(string username, string password)
    {
        var user = await _userManager.FindByNameAsync(username);
        if (user != null)
        {

            var result = await _signInManager.PasswordSignInAsync(user, password, false, false);

            if (result.Succeeded)
            {
                return new JsonResult(true, new JsonSerializerSettings());
            }
        }

        return new JsonResult(false, new JsonSerializerSettings());
    }

这是前端调用

 handleLogin(event) {
 event.preventDefault();
 const data = new FormData(event.target);

 fetch('https://localhost:5001/login', {
  method: 'POST',
  body: data
 })
  .then(response => response.json())
  .then(data => {
    console.log(data);
    if (data)
      history.push('/home');
  });
 }

如有任何帮助,将不胜感激。

【问题讨论】:

  • UseAuthentication 中间件放在 UseCookiePolicyUseCors 之间,并确保你有 Set-Cookie 回复中的标题。

标签: c# reactjs asp.net-core session-cookies


【解决方案1】:

默认情况下,fetch api不实现cookie。

试试这个

fetch('https://localhost:5001/login', {
  method: 'POST',
  body: data,
  credentials: "same-origin"
 })
  .then(response => {
    document.cookie = `coo_key=${response.headers.get('cookiee_key')};max-age=604800;domain=yoururl.com`;
    return response.json();
 })
  .then(data => {
    console.log(data);
    if (data)
      history.push('/home');
  });
 }

虽然这只会让您访问由 api 生成的 cookie。然后你必须手动设置它

document.cookie = `coo_key=${response.headers.get('cookiee_key')};max-age=604800;domain=yoururl.com`

TLDR 从 api 生成的 cookie 不会自动绑定到您的 react 应用程序中。如果他们分开。需要自己开启同源并设置cookie

【讨论】:

  • 不幸的是它没有改变任何东西
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 2019-06-21
  • 2023-01-16
  • 2018-06-14
  • 2011-10-26
  • 1970-01-01
  • 2012-01-11
相关资源
最近更新 更多