c# - 登录后 User.Identity.Name 为空,但 User.Identity.IsAuthenticated 设置正确
问题描述
应用程序是在 Razor Pages ASP.NET Core 中开发的
我以这种方式通过 LDAP 登录用户:
public async Task<IActionResult> OnPostAsync()
{
var user = authService.Login(UserName, Password);
if (null != user)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, UserName),
};
ClaimsIdentity identity = new ClaimsIdentity(claims, "Cookies", "user", "role");
await HttpContext.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookies", "user", "role")));
}
else
{
return Unauthorized();
}
return Redirect("~/Index");
}
这就是 Startup.cs 的外观
services.Configure<LdapConfig>(Configuration.GetSection("Ldap"));
services.AddScoped<IAuthenticationService, LdapAuthenticationService>();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
options.LoginPath = "/Account/SignIn";
});
services
.ConfigureApplicationCookie(options =>
{
options.Cookie.Name = "TicketTracker.ldap.identity";
options.Cookie.HttpOnly = true;
options.Cookie.Expiration = TimeSpan.FromDays(150);
options.LoginPath = "/Account/Signin"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
options.LogoutPath = "/Account/Signout"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
options.AccessDeniedPath = "/Account/AccessDenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
options.SlidingExpiration = true;
options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
});
关于身份验证一切正常,但我无法访问已登录的当前用户的名称。
有人知道该怎么做吗?
谢谢!
解决方案
问题解决了自己感谢没有帮助!
options.Cookie.Name = "TicketTracker.ldap.identity";
就在这一行,我只是将其替换为
options.Cookie.Name = ".AspNetCore.Cookies";
因为 cookie 的名称是由我通过 SignInAsync 方法传递的声明身份创建的。
现在工作正常。
推荐阅读
- visual-studio-code - VS-Code 集成终端中的 ZSH agnoster 主题不显示符号
- java - Java 检测屏幕事件
- c# - xamarin 表单主详细信息页面 - 空异常 sqlite
- javascript - 未从角度 5 中的单击函数调用函数
- python - URL中的Django意外字符
- uwp - 如何将 IntPtr 写入 UWP 中的文件
- php - PHP 服务器发送事件连接不会关闭?
- ajax - Django Ajax 表单提交错误地重定向到另一个页面
- javascript - Javascript HTML5 视频事件不能在 Safari 上触发
- docker-compose - 在 circleci 的 docker executor 中使用 docker-compose 进行网络连接