![](/img/trans.png)
[英]ASP.NET Core 2.0 custom middleware using cookie authentication
[英]Asp.Net Core 2.0 Cookie Authentication Expires Before Time
我有一個使用Cookie身份驗證的MVC Asp.Net Core 2.0應用程序。 問題是會話提前過期,並將用戶重定向到登錄路徑,從而迫使他再次進行身份驗證。
我的啟動班:
ConfigureServices方法:
const string schema = "adminScheme";
services.AddAuthentication(schema).AddCookie(schema, options =>
{
options.AccessDeniedPath = new PathString("/Account/AcessoNegado");
options.Cookie = new CookieBuilder
{
HttpOnly = true,
Name = ".Admin.Security.Cookie",
Path = "/",
SameSite = SameSiteMode.Lax,
SecurePolicy = CookieSecurePolicy.SameAsRequest
};
options.ExpireTimeSpan = TimeSpan.FromMinutes(480);
options.LoginPath = new PathString("/Account/Login");
options.LogoutPath = new PathString("/Account/Logout");
options.ReturnUrlParameter = "RequestPath";
options.SlidingExpiration = true;
});
在配置方法上:
app.UseAuthentication();
我的登錄方式:
var cadastro = user.FirstOrDefault();
const string Issuer = "adminScheme";
List<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.Name, cadastro.NomeUsuario, ClaimValueTypes.String, Issuer),
new Claim("Idusuario",cadastro.Id.ToString(), ClaimValueTypes.String, Issuer),
new Claim("IdtipoUsuario", cadastro.IdtipoUsuario.ToString(), ClaimValueTypes.String, Issuer)
};
ClaimsIdentity identity = new ClaimsIdentity(claims, "cookie");
ClaimsPrincipal principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(scheme: Issuer,
principal: principal,
properties: new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTime.UtcNow.AddMinutes(480)
});
return RedirectToLocal(returnUrl);
我在控制器中使用[授權]。
我剛試過你的代碼。 如果您使用的是2.0.x
版本,請如下更改代碼:
//ClaimsIdentity identity = new ClaimsIdentity(claims, "cookie");
ClaimsIdentity identity = new ClaimsIdentity(claims, "adminScheme");
現在,它對我來說完美無瑕。
順便說一句, 2.0
版本已在2018年10月1日終止生命。建議遷移到2.1.x
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.