[英]Using the Authorize Attribute with Custom Cookie Authentication in 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;
});
}
然后,出于测试目的,我有一个登录页面,您只需单击一个按钮,它就会回复自身,并在控制器中显示此代码。
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]
属性不起作用?
我认为你需要在身份的构造函数中指定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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.