使用ASP.NET 5中的Cookie身份验证重定向到使用属性授权登录

时间:2015-12-23 14:01:56

标签: c# asp.net-core asp.net-core-mvc

我正在测试 [授权] 属性,但如果用户尚未登录(Chrome检查员返回401),则无法重定向到登录页面。

这是我在控制器中登录的代码(非常简单)。

if (model.UserName == "admin" && model.Password == "test")
{
    var claims = new[] { new Claim("name", model.UserName), new Claim(ClaimTypes.Role, "Admin") };
    var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
    await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
    return RedirectToAction("Index", "Home");
}

这是我在登录的 Startup.cs 中的配置:

app.UseCookieAuthentication(options =>
    {
        options.AutomaticAuthenticate = true;
        options.LoginPath = new PathString("/Account/Login");
    });

有什么想法吗?

谢谢!

2 个答案:

答案 0 :(得分:7)

您的Startup.cs应如下所示:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    LoginPath = "/account/login",

    AuthenticationScheme = "Cookies",
    AutomaticAuthenticate = true,
    AutomaticChallenge = true
});

设置AutomaticChallenge是使[Authorize]属性起作用的原因。确保在要重定向(302)的任何控制器上包含[Authorize]属性。

此GitHub仓库中有一个非常基本的示例可能会提供一些指导: https://github.com/leastprivilege/AspNet5TemplateCookieAuthentication

答案 1 :(得分:1)

Startup.cs

中尝试此操作
app.UseCookieAuthentication(options =>
{
   options.AuthenticationType = CookieAuthenticationDefaults.AuthenticationScheme;
   options.AutomaticAuthenticate = true;
   options.AutomaticChallenge = true;
   options.LoginPath = new PathString("/Account/Login");
});

这是在控制器

IAuthenticationManager authManager = Request.GetOwinContext().Authentication;
authManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);