StartUp.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie((options) =>
{
options.Cookie.Domain = "localhost";
options.Cookie.Name = "mycookie";
options.Cookie.Path = "/";
options.Cookie.HttpOnly = true;
options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Lax;
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Accounts}/{action=Index}/{id?}");
});
}
Controller.cs
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, authUserNameBuilder.ToString())
};
var claimsIdentity = new ClaimsIdentity(claims,CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
new AuthenticationProperties{
IsPersistent = false
}
);
StartUp.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie((options) =>
{
options.Cookie.Domain = "localhost";
options.Cookie.Name = "mycookie";
options.Cookie.Path = "/";
options.Cookie.HttpOnly = true;
options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Lax;
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Accounts}/{action=Index}/{id?}");
});
}
Controller.cs
foreach (var claims in HttpContext.User.Claims)
{
Debug.WriteLine(claims.Value);
}
在应用程序1的Controller.cs中,我使用Cookie身份验证创建Cookie,如代码所示。
在应用程序1和应用程序2中,Startup.cs是相同的。
在Application 2的Controller.cs中,我试图使用For循环在应用程序1中创建Cookie,如代码所示。
但是我无法在Application1中创建的应用程序2中获取cookie。请建议。
参考:https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?tabs=aspnetcore2x