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

rgv*_*sar 4 c# asp.net authentication asp.net-core-mvc asp.net-core

我在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;
    });
}
Run Code Online (Sandbox Code Playgroud)

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

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");
}
Run Code Online (Sandbox Code Playgroud)

这是HomeController.cs

[Authorize]
public async Task<IActionResult> Index()
{
    return View();
}
Run Code Online (Sandbox Code Playgroud)

我得到401未经授权.根据我的理解,SignInAsync呼叫应该对用户进行身份验证,并且该[Authorize]属性应该允许任何经过身份验证的用户.如果我在HomeController.cs中做这样的事情:

ClaimsPrincipal cp = await HttpContext.Authentication.AuthenticateAsync("MyAuthenticationScheme");
Run Code Online (Sandbox Code Playgroud)

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

Joe*_*tte 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");
Run Code Online (Sandbox Code Playgroud)