我已经设置了一个新的asp.NET Core web项目。我想要自定义身份验证,我创建自己的cookie并为用户分配声明。这是相当直接的设置。
我的Startup.cs代码如下所示:
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.Configure<CookieAuthenticationOptions>(options =>
{
options.LoginPath = new PathString("/account/login");
options.AccessDeniedPath = new PathString("/account/accessdenied");
options.AutomaticChallenge = true;
});
services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly", policy => {
policy.RequireClaim(ClaimTypes.Role, "admin"); });
});
}
public void Configure(IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseStaticFiles();
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
LoginPath = new PathString("/account/login"),
AccessDeniedPath = new PathString("/account/accessdenied"),
AutomaticChallenge = true
});
app.UseMvcWithDefaultRoute();
}
}
然后我设置了以下登录方法:
[HttpPost]
public async Task<IActionResult> Login(string userName,
string password, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (!string.IsNullOrEmpty(userName) && userName == password)
{
List<Claim> claims;
switch (userName)
{
case "admin":
claims = new List<Claim>
{
new Claim("sub", "2"),
new Claim("name", "Bob"),
new Claim("email", "bob@smith.com"),
new Claim("status", "junior"),
new Claim("department", "sales"),
new Claim("region", "north"),
new Claim("role", "supervisor"),
new Claim(ClaimTypes.Role, "admin")
};
break;
default:
claims = new List<Claim>
{
new Claim("sub", "3"),
new Claim("name", userName),
new Claim("email", userName + "@smith.com"),
new Claim("status", "intern"),
new Claim("department", "development"),
new Claim(ClaimTypes.Role, "client")
};
break;
}
var id = new ClaimsIdentity(claims, "local");//, "local", "name", "role"
await HttpContext.Authentication.SignInAsync("Cookies",
new ClaimsPrincipal(id));
return LocalRedirect("/Home/Index");
}
return View();
}
一切正常,并且在任何控制器方法上放置[Authorize]属性,除非您已登录,否则会停止访问,如下所示:
[Authorize]
public IActionResult AccessibleToLoggedIn()
{
ViewData["Message"] = "Example - open to any logged in user!";
return View();
}
[Authorize(Policy ="AdminOnly")]
public IActionResult AdminPage()
{
ViewData["Message"] = "Admin only page";
return View();
}
到目前为止一切听起来都不错......
我努力工作的一件事 - 当用户尝试使用附加的[Authorize]属性访问视图时,它们不会被重定向到登录页面。
我做错了什么?
我希望以后能够将用户重定向到访问被拒绝页面,因为它们与我打算定义的特定策略不匹配。
提前感谢任何指针!