简体   繁体   English

ASP.Net Core 2身份验证

[英]ASP.Net Core 2 authentication

I am lost with authentification in ASP.Net Core 2 MVC Applications. 我迷失于ASP.Net Core 2 MVC应用程序中的身份验证。 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. 我正在使用Core 2版本,似乎在版本1和版本2之间有很多更改。我已经阅读了一些实际上没有用的教程。

First of all, here is what i put in Startup.cs in ConfigureServices() method: 首先,这是我在ConfigureServices()方法中放入Startup.cs的内容

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: 这是我放入Configure()方法的内容:

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 InvalidOperationException:未配置身份验证处理程序来处理方案:Cookies

Any idea of what is wrong ? 知道什么是错的吗?

In your Configure() method change app.UseIdentity() to: 在您的Configure()方法中,将app.UseIdentity()更改为:

app.UseAuthentication();

Also, note : If you are using cookies without Identity (as it appears in your Index action): 另外,请注意 :如果您使用的是不带身份的Cookie(如“ Index操作中所示):

Invoke the AddAuthentication and AddCookie methods in the ConfigureServices method: ConfigureServices方法中调用AddAuthenticationAddCookie方法:

 // 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 其他阅读:将身份验证和身份迁移到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. 我以自己执行Logout()动作的方式修复了该问题,该动作删除了身份验证Cookie,然后重定向到起始页。 To do it reliably I gave the auth. 为了可靠地做到这一点,我给了认证。 cookie my own name using the ConfigureServices() method in Startup.cs . 使用Startup.csConfigureServices()方法对我自己的名称进行cookie。

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: 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. 也许这为我节省了一些时间,因为我花了很多时间到达那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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