我目前正在开发一个不使用 Identity 的项目。
问题是这个项目应该有一个记住我的选项,允许用户自动重新连接到网站。
我的问题是我找不到任何完整的教程来创建没有身份的 cookie。
如果有人有很好的代码示例或教程:)
谢谢
最佳答案
在我的项目中,我使用 AngularJS 作为前端,使用 .Net Core API 作为后端。
因此,我不需要为 AccessDeniedPath
、LoginPath
等配置页面。
这就是我所做的:
在启动类中配置cookie:
public void Configure(IApplicationBuilder app) { //... CookieAuthenticationOptions options = new CookieAuthenticationOptions(); options.AuthenticationScheme = "MyCookie"; options.AutomaticAuthenticate = true; options.CookieName = "MyCookie"; app.UseCookieAuthentication(options); //... }
登录是这样的:
[HttpPost, Route("Login")] public IActionResult LogIn([FromBody]LoginModel login) { //... var identity = new ClaimsIdentity("MyCookie"); //add the login as the name of the user identity.AddClaim(new Claim(ClaimTypes.Name, login.Login)); //add a list of roles foreach (Role r in someList.Roles) { identity.AddClaim(new Claim(ClaimTypes.Role, r.Name)); } var principal = new ClaimsPrincipal(identity); HttpContext.Authentication.SignInAsync("MyCookie", principal).Wait(); return Ok(); }
注销是这样的:
[HttpPost, Route("Logout")] public async Task<IActionResult> LogOut() { await HttpContext.Authentication.SignOutAsync("MyCookie"); return Ok(); }
然后你可以像这样使用它:
[HttpPost] [Authorize(Roles = "Role1,Role2,Role3")] public IActionResult Post() { //... string userName = this.User.Identity.Name; //... }
*请注意该方法仅被授权给“Role1、Role2 和 Role3”。并查看如何获取用户名。
关于c# - 没有身份的 Cookie Asp.net core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40935872/