【问题标题】:ASP.Net Core 2 authenticationASP.Net Core 2 身份验证
【发布时间】:2018-05-13 16:08:00
【问题描述】:

我迷失了 ASP.Net Core 2 MVC 应用程序中的身份验证。 我正在使用 Core 2 版本,版本 1 和 2 之间似乎有很多变化。我已经阅读了一些不太有效的教程。

首先,这是我在 Startup.csConfigureServices() 方法的内容:

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

这是我在Configure() 方法中输入的内容:

app.UseIdentity();

我在每个控制器的每个动作方法上都放了这个注解:

[Authorize]

这是我在我的 post action 登录方法中所做的:

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

当我尝试登录时出现此异常:

InvalidOperationException:没有配置身份验证处理程序来处理方案:Cookies

知道什么是错的吗?

【问题讨论】:

标签: c# asp.net-core asp.net-core-2.0 asp.net-core-identity


【解决方案1】:

在您的Configure() 方法中将app.UseIdentity() 更改为:

app.UseAuthentication();

另外,请注意:如果您使用没有身份的 cookie(因为它显示在您的 Index 操作中):

调用 AddAuthenticationAddCookieConfigureServices方法:

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

补充阅读:Migrating Authentication and Identity to ASP.NET Core 2.0

【讨论】:

  • @Bob5421:如果您使用没有身份的 cookie,则需要在 ConfigureServices 中添加 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)。查看更新的答案和Migrating Authentication and Identity to ASP.NET Core 2.0
  • 其实我不明白cookies和身份的区别。我想要的是使用 php 中的会话进行身份验证 :)
  • 你应该阅读这个Introduction to Identity on ASP.NET Core。是HttpContext.Authentication.SignInAsync 行导致了您的问题。如果你想使用身份,你应该使用SignInManager.SignInAsync()
  • 你说的很对。这就是问题所在。但我不明白为什么 HttpContext.Authentication.SignInAsync 不起作用!
  • 它不起作用,因为您没有在Startup 中注册名称由CookieAuthenticationDefaults.AuthenticationScheme(“Cookies”)定义的身份验证方案,所以当您尝试使用该方案登录时,除了抛出异常之外别无他法。只要您在启动时使用AddAuthentication() 注册它们,您就可以很高兴地使用任意数量的方案(例如身份、基本身份验证...)进行身份验证。
【解决方案2】:

我以我自己的 Logout() 操作的方式对其进行了修复,该操作删除了身份验证 cookie,然后重定向到起始页面。为了可靠地做到这一点,我给出了身份验证。使用Startup.cs 中的ConfigureServices() 方法将我自己的名字cookie。

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

也许这可以节省一些时间,因为我花了很多时间到达那里。

【讨论】:

    猜你喜欢
    • 2018-02-23
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 2018-06-25
    • 2016-05-19
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多