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

然后只是为了测试目的,我有一个登录页面,您只需单击一个按钮,它就会发回自己,在 Controller 中使用此代码。

登录 Controller .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] 属性不起作用?

最佳答案

我认为您需要在身份的构造函数中指定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");

关于c# - 在 ASP.NET Core 中使用具有自定义 Cookie 身份验证的授权属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36230164/

10-09 18:11
查看更多