【问题标题】:ReactJS .NET not able to set cookieReactJS .NET 无法设置 cookie
【发布时间】:2021-04-16 15:55:38
【问题描述】:

我有一个允许 CORS 的 .NET5 API 和一个使用 axios 向 API 发出请求的反应应用程序。 我想在我的控制器中设置一个 HTTPOnly Cookie,但 Response.Cookies.Append("refreshToken", token, cookieOptions) 由于某种原因无法正常工作,当我进入 Chrome 的“应用程序”选项卡时,我的 cookie 不存在。

我在 Controller 中的代码如下所示:

var cookieOptions = new CookieOptions
{
    HttpOnly = true,
    Expires = DateTime.UtcNow.AddDays(7),
    IsEssential = true,
    SameSite = SameSiteMode.Lax,
};
Response.Cookies.Append("refreshToken", token, cookieOptions);

我的Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy(name: MyCorsPolicy,
            builder =>
            {
                builder
                    .WithOrigins("http://localhost:3000")
                    .AllowAnyHeader()
                    .AllowAnyMethod();
        });
    });

        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.AddControllers();
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("ConnStr"), b =>
            b.MigrationsAssembly("Template_Data")));

        var appSettingsConfig = Configuration.GetSection("AppSettings");
        services.Configure<AppSettings>(appSettingsConfig);

        services.AddScoped<IIdentityService, IdentityService>();

        // For Identity  
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        var tokenValidationParameters = new TokenValidationParameters()
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidAudience = Configuration["AppSettings:JWT:ValidAudience"],
            ValidIssuer = Configuration["AppSettings:JWT:ValidIssuer"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["AppSettings:JWT:SecretKey"])),
            // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
            ClockSkew = TimeSpan.Zero
        };

        services.AddSingleton(tokenValidationParameters);

        // Adding Authentication  
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(options =>
        {
            options.SaveToken = true;
            options.RequireHttpsMetadata = false;
            options.TokenValidationParameters = tokenValidationParameters;
        });

    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();

            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ASP.NET 5 Web API v1"));
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors(MyCorsPolicy);

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

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

【问题讨论】:

    标签: .net reactjs cookies cross-domain setcookie


    【解决方案1】:

    我通过在我的 Startup.cs 中添加 .AllowCredentials() 来解决,如下所示:

    services.AddCors(options =>
    {
        options.AddPolicy(name: MyCorsPolicy,
            builder =>
            {
                builder
                    .WithOrigins("http://localhost:3000")
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials();
        });
    });
    

    在我的 react 应用程序中,我在导入和设置 axios 的文件中添加了 axios.defaults.withCredentials = true;

    【讨论】:

      猜你喜欢
      • 2018-11-28
      • 1970-01-01
      • 1970-01-01
      • 2021-05-28
      • 2021-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多