【发布时间】: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 中间件放在 UseCookiePolicy 和 UseCors 之间,并确保你有 Set-Cookie 回复中的标题。
标签: c# reactjs asp.net-core session-cookies