.Net Core 3.0 Cookie 验证。授权属性总是重定向
.Net Core 3.0 Cookie Auth. Authorize Attribute always redirecting
我终于开始将一些 .Net Framework 项目转换为 Core (3.0)。我目前正在查看 Cookie 身份验证并获取一个简单示例 运行。
我有使用有效数据创建的声明和登录 cookie,但任何使用 [Authorize] 的控制器操作总是重定向到登录页面(表明我们未登录)。但是,在登录页面上,我输出了声明和 IsAuthenticated 状态及其 returns 有效数据。
登录功能
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, "ID"),
new Claim(ClaimTypes.Name, "TEST"),
new Claim(ClaimTypes.GivenName, "Test"),
new Claim(ClaimTypes.Surname, "TEST"),
new Claim(ClaimTypes.DateOfBirth, DateTime.Now.ToString("o"), ClaimValueTypes.DateTime)
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(principal);
示例'Secure Area'
[Authorize()]
public IActionResult Secure()
{
return View();
}
配置服务:
services.AddControllersWithViews();
services.AddMvc();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "TestAuthCookie";
options.LoginPath = "/Home/Login";
options.LogoutPath = "/Home/Logout";
});
在启动时配置。
根据评论:有时人们忘记在中间件管道的早期阶段调用 app.UseAuthentication();
,因此 HttpContext.User
不会被正确设置。
app.UseAuthentication(); // this line is important
app.UseAuthorization();
个人而言,当认证不起作用时,我会首先检查是否启用了AuthenticationMiddleware
我终于开始将一些 .Net Framework 项目转换为 Core (3.0)。我目前正在查看 Cookie 身份验证并获取一个简单示例 运行。
我有使用有效数据创建的声明和登录 cookie,但任何使用 [Authorize] 的控制器操作总是重定向到登录页面(表明我们未登录)。但是,在登录页面上,我输出了声明和 IsAuthenticated 状态及其 returns 有效数据。
登录功能
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, "ID"),
new Claim(ClaimTypes.Name, "TEST"),
new Claim(ClaimTypes.GivenName, "Test"),
new Claim(ClaimTypes.Surname, "TEST"),
new Claim(ClaimTypes.DateOfBirth, DateTime.Now.ToString("o"), ClaimValueTypes.DateTime)
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(principal);
示例'Secure Area'
[Authorize()]
public IActionResult Secure()
{
return View();
}
配置服务:
services.AddControllersWithViews();
services.AddMvc();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "TestAuthCookie";
options.LoginPath = "/Home/Login";
options.LogoutPath = "/Home/Logout";
});
在启动时配置。
根据评论:有时人们忘记在中间件管道的早期阶段调用 app.UseAuthentication();
,因此 HttpContext.User
不会被正确设置。
app.UseAuthentication(); // this line is important app.UseAuthorization();
个人而言,当认证不起作用时,我会首先检查是否启用了AuthenticationMiddleware