web-dev-qa-db-fra.com

Cookie d'authentification ASP.NET Core 2.0 non défini

J'ai suivi cet article ( https://docs.Microsoft.com/en-us/aspnet/core/security/authentication/cookie?tabs=aspnetcore2x ) de Microsoft pour migrer ma procédure d'authentification dans mon .NET Core 2.0 Application MVC.

Startup.cs (ConfigureServices)

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

services.AddAuthentication("MyCookieAuthenticationScheme")
        .AddCookie("MyCookieAuthenticationScheme", options => {
            options.AccessDeniedPath = "/Account/Forbidden/";
            options.LoginPath = "/Account/Login/";
        });

Startup.cs (Configure)

app.UseAuthentication();

AccountController.cs

List<Claim> claims = new List<Claim> {
                        new Claim(ClaimTypes.Name, "testUser"),
                        new Claim(ClaimTypes.Email, model.Email),
                        //new Claim("ID", user.ID.ToString(), ClaimValueTypes.Integer),
                        new Claim(ClaimTypes.Role, "Admin")
                    };

ClaimsIdentity identity = new ClaimsIdentity(claims, "MyCookieAuthenticationScheme");

ClaimsPrincipal principal = new ClaimsPrincipal(identity);

await HttpContext.SignInAsync("MyCookieAuthenticationScheme", principal, new AuthenticationProperties
{
    IsPersistent = false
});

Malheureusement, mon cookie .NET n'est jamais défini. Cela signifie que User.Identity.IsAuthenticated est toujours faux. J'ai essayé de nombreuses options de cookie, comme changer Cookie.SameSite ou Cookie.SecurePolicy en toutes les valeurs possibles.

Je travaille avec Visual Studio 2017, hôte local sur https, Chrome 61.

4
Bluesight

Je pense que vous devriez fournir un processus de connexion utilisant la classe UserManager d'Identity au lieu de HttpContext.SignInAsync. Injectez IUserManager au constructeur de votre contrôleur et utilisez-le pour vous connecter.

AccountController: Controller
{
    private readonly SignInManager<ApplicationUser> _signInManager;

    public AccountController(SignInManager<ApplicationUser> singInManager)
    {
        _signInManager = signInManager;
    }

    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
        ...
    }

}

Vous pouvez modifier les paramètres de cookie d'Identity dans votre fichier Startup.cs. Jeter un coup d'oeil:

https://docs.Microsoft.com/en-us/aspnet/core/security/authentication/identity

1
Orhun