共享在一个中创建的cookie并在另一个中使用它在asp.net core mvc 2.0中使用没有ASP.NET核心身份的Cookie身份验证?

时间:2018-01-24 11:55:19

标签: cookies asp.net-core-mvc-2.0

申请1:

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
    }
);

申请2:

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

0 个答案:

没有答案