简体   繁体   中英

ASP.Net Core 2 authentication

I am lost with authentification in ASP.Net Core 2 MVC Applications. I am working with Core 2 version and it seems there are a lot of changes between version 1 and 2. I have read some tutorials which does not really works.

First of all, here is what i put in Startup.cs in ConfigureServices() method:

services.AddIdentity<MyUserClass, IdentityRole>()
                .AddEntityFrameworkStores<MyDatabaseEFContext>()
                .AddDefaultTokenProviders();

services.ConfigureApplicationCookie(options =>
            {
                // Cookie settings
                options.Cookie.HttpOnly = true;
                options.Cookie.Expiration = TimeSpan.FromDays(150);
                options.LoginPath = "/Account/Login"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
                options.LogoutPath = "/Account/Logout"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
                options.AccessDeniedPath = "/Account/AccessDenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
                options.SlidingExpiration = true;
            });

and here is what i put in Configure() method:

app.UseIdentity();

I put this annotation on each action method of each controller:

[Authorize]

And here is what i've done in my post action login method:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    var claims = new List<Claim> {new Claim(ClaimTypes.Name, model.Login)};
    var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
    var principal = new ClaimsPrincipal(identity);

    await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

    return RedirectToAction("Index", "PrivateController");
}

I get this exception when i try to login:

InvalidOperationException: No authentication handler is configured to handle the scheme: Cookies

Any idea of what is wrong ?

In your Configure() method change app.UseIdentity() to:

app.UseAuthentication();

Also, note : If you are using cookies without Identity (as it appears in your Index action):

Invoke the AddAuthentication and AddCookie methods in the ConfigureServices method:

 // If you don't want the cookie to be automatically authenticated and assigned to HttpContext.User, // remove the CookieAuthenticationDefaults.AuthenticationScheme parameter passed to AddAuthentication. services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/Account/LogIn"; options.LogoutPath = "/Account/LogOff"; }); 

Additional reading: Migrating Authentication and Identity to ASP.NET Core 2.0

I fixed it the way I do my own Logout() action which deletes the authentication cookie and then redirects to the start page. To do it reliably I gave the auth. cookie my own name using the ConfigureServices() method in Startup.cs .

Startup.cs:

    private void ConfigureServices(IServiceCollection services)
    {
        ..

        services.ConfigureApplicationCookie(options =>
        {
            // Cookie settings
            options.Cookie.HttpOnly = true;
            options.ExpireTimeSpan = TimeSpan.FromMinutes(30);

            options.LoginPath = "/Identity/Account/Login";
            options.AccessDeniedPath = "/Identity/Account/AccessDenied";
            options.SlidingExpiration = true;
            options.Cookie.Name = "MyOwnCookieName";
        });
        ...

HomeController.cs:

    [Authorize]
    [HttpGet]
    public IActionResult Logout()
    {
        Response.Cookies.Delete("MyOwnCookieName");
        return RedirectToAction("Index");
    }

Maybe this saves someone some time as I used a lot of time to get there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM