ReactJS .NET 无法设置 cookie
ReactJS .NET not able to set cookie
我有一个允许 CORS 的 .NET5 API 和一个使用 axios 向 API 发出请求的 React 应用程序。
我想在我的控制器中设置一个 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();
});
}
我通过在我的 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;
。
我有一个允许 CORS 的 .NET5 API 和一个使用 axios 向 API 发出请求的 React 应用程序。
我想在我的控制器中设置一个 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();
});
}
我通过在我的 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;
。