在ASP.NET Core中使用授权属性和自定义Cookie身份验证

时间:2016-03-26 00:24:26

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

我在Startup.cs中有以下代码:

public void ConfigureServices(IServiceCollection services)
{
    //Other middleware
    services.AddAuthentication(options =>
    {
        options.SignInScheme = "MyAuthenticationScheme";
    });

    services.AddAuthorization();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    //Other configurations.
    app.UseCookieAuthentication(options =>
    {
        options.AuthenticationScheme = "MyAuthenticationScheme";
        options.LoginPath = new PathString("/signin/");
        options.AccessDeniedPath = new PathString("/signin/");
        options.AutomaticAuthenticate = true;
    });
}

然后仅出于测试目的,我有一个登录页面,您只需单击一个按钮,它就会回复自身,并在控制器中显示此代码。

SignInController.cs

public IActionResult Index()
{
    return View();
}

[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Index(SignInViewModel model)
{
    List<Claim> claimList = new List<Claim>();
    claimList.Add(new Claim("Admin", "true"));
    ClaimsIdentity identity = new ClaimsIdentity(claimList);
    ClaimsPrincipal principal = new ClaimsPrincipal(identity);
    await HttpContext.Authentication.SignInAsync("MyAuthenticationScheme", principal);
    return RedirectToAction(nameof(HomeController.Index), "Home");
}

这里是HomeController.cs

[Authorize]
public async Task<IActionResult> Index()
{
    return View();
}

我未经授权获得401。根据我的理解,SignInAsync调用应该对用户进行身份验证,[Authorize]属性应该允许任何经过身份验证的用户。如果我在HomeController.cs中执行类似的操作:

ClaimsPrincipal cp = await HttpContext.Authentication.AuthenticateAsync("MyAuthenticationScheme");

我可以看到cp确实包含我之前提供的Admin声明。我认为这意味着用户已成功通过身份验证。为什么[Authorize]属性不起作用?

1 个答案:

答案 0 :(得分:7)

我认为你需要在身份的构造函数中指定authscheme,你的代码应该更像这样:

var authProperties = new AuthenticationProperties();
var identity = new ClaimsIdentity("MyAuthenticationScheme");
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "1"));
identity.AddClaim(new Claim(ClaimTypes.Name, "Admin"));
var principal = new ClaimsPrincipal(identity);
await HttpContext.Authentication.SignInAsync(
            "MyAuthenticationScheme", 
            claimsPrincipal, 
            authProperties);
return RedirectToAction(nameof(HomeController.Index), "Home");