我目前正在开发一个不使用身份的项目。
问题是这个项目应该有一个记住我的选项,允许用户自动重新连接到网站。
我的问题是我找不到任何完整的教程来创建没有身份的 cookie。
如果有人有很好的代码示例或教程:)
Thanks
在我的项目中,我使用 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”。并查看如何获取用户名。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)