我目前正在开发一个不使用身份的项目。Cookie无身份Asp.net核心
事情是,这个项目应该有一个记住我的选项,允许用户自动重新连接到网站。
我的问题是,我找不到任何完整的tutoriel来创建一个没有身份的cookie。
如果有人有代码或教学课程:)
感谢
我目前正在开发一个不使用身份的项目。Cookie无身份Asp.net核心
事情是,这个项目应该有一个记住我的选项,允许用户自动重新连接到网站。
我的问题是,我找不到任何完整的tutoriel来创建一个没有身份的cookie。
如果有人有代码或教学课程:)
感谢
在灯架上有一个在这里相当好文章一个很好的例子:Using Cookie Middleware without ASP.NET Core Identity。
基本上你所做的是设置cookie处理中间件就好像你要识别用户,但是你只是创建一个ClaimsPrincipal对象而不要求用户登录。您将该对象传递给SigninAsync方法,并为您创建cookie。如果你按照这篇文章,你应该没问题。
我已经按照文档的文章,对我来说不是我期望从一个或两个值设置一个基本的cookie来重新连接用户。 – OrcusZ
是的,它看起来有点复杂,但我认为如果你自己实现了一切,你最终会得到类似的结果。您仍然可以通过HttpContext.Response.Cookies访问Cookie。如果您在使用Intellisense的MVC控制器中采取行动,那么您会在该处看到它。但是您需要每个请求的信息,因此您需要创建一些中间件,并将其放置在管道的前端,以访问上下文并在Cookie到达任何控制器之前对其进行管理。所以你最终会写一些类似文章中的中间件组件。 – GlennSills
在我的项目中,我使用AngularJS作为前端和.Net核心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”。并了解如何获取用户名。
我想你是问如何在用户使用“记住我?”登录时制作持久性cookie。复选框已选中。
所有答案都在正确的路径上 - 您最终会调用HttpContext.Authentication.SignInAsync
,但Cookie中间件默认会发出会话Cookie。您需要将身份验证属性作为第三个参数传递,以使Cookie保持不变,例如:
HttpContext.Authentication.SignInAsync(
Options.Cookies.ApplicationCookieAuthenticationScheme,
userPrincipal,
new AuthenticationProperties { IsPersistent = isPersistent });
编写cookie:https://msdn.microsoft.com/zh-cn/library/aa287547( v = vs.71).aspx阅读一个cookie:https://msdn.microsoft.com/en-us/library/aa287533(v=vs.71).aspx – Kevin
我有一个简单的cookie auth解决方案示例https: //github.com/joeaudette/cloudscribe.Web.SimpleAuth –