app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "MyCookieMiddlewareInstance",
LoginPath = new PathString("/Account/Unauthorized/"),
AccessDeniedPath = new PathString("/Account/Forbidden/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
Task ValidateAsync(CookieValidatePrincipalContext context);
public static class LastChangedValidator
{
public static async Task ValidateAsync(CookieValidatePrincipalContext context)
{
// Pull database from registered DI services.
var userRepository = context.HttpContext.RequestServices.GetRequiredService<IUserRepository>();
var userPrincipal = context.Principal;
// Look for the last changed claim.
string lastChanged;
lastChanged = (from c in userPrincipal.Claims
where c.Type == "LastUpdated"
select c.Value).FirstOrDefault();
if (string.IsNullOrEmpty(lastChanged) ||
!userRepository.ValidateLastChanged(userPrincipal, lastChanged))
{
context.RejectPrincipal();
await context.HttpContext.Authentication.SignOutAsync("MyCookieMiddlewareInstance");
}
}
}
app.UseCookieAuthentication(options =>
{
options.Events = new CookieAuthenticationEvents
{
// Set other options
OnValidatePrincipal = LastChangedValidator.ValidateAsync
};
});
await HttpContext.Authentication.SignInAsync(
"MyCookieMiddlewareInstance",
principal,
new AuthenticationProperties
{
IsPersistent = true
});
await HttpContext.Authentication.SignInAsync(
"MyCookieMiddlewareInstance",
principal,
new AuthenticationProperties
{
ExpiresUtc = DateTime.UtcNow.AddMinutes(20)
});
// 1. 在Startup.cs的Configure方法中加上
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "UserAuth", // Cookie 验证方案名称,在写cookie时会用到。
AutomaticAuthenticate = true, // 是否自动启用验证,如果不启用,则即便客服端传输了Cookie信息,服务端也不会主动解析。除了明确配置了 [Authorize(ActiveAuthenticationSchemes = "上面的方案名")] 属性的地方,才会解析,此功能一般用在需要在同一应用中启用多种验证方案的时候。比如分Area.
LoginPath = "/User/Index" // 登录页
});
// 2. 新建UserController
// 3. 创建一个测试登录的方法(这里为了方便测是我用的是get方法,方便传参请求)
public IActionResult Login(int userId, string userName)
{
WriteUser(userId, userName);
return Content("Write");
}
private async void WriteUser(int userId, string userName)
{
var identity = new ClaimsIdentity("Forms"); // 指定身份认证类型
identity.AddClaim(new Claim(ClaimTypes.Sid, userId.ToString())); // 用户Id
identity.AddClaim(new Claim(ClaimTypes.Name, userName)); // 用户名称
var principal = new ClaimsPrincipal(identity);
await HttpContext.Authentication.SignInAsync("UserAuth", principal, new AuthenticationProperties { IsPersistent = true , ExpiresUtc = DateTime.UtcNow.AddMinutes(20) }); //过期时间20分钟
}
// 4. 创建一个退出登录的方法
public async Task<ActionResult> Logout()
{
await HttpContext.Authentication.SignOutAsync("UserAuth"); // Startup.cs中配置的验证方案名
return RedirectToAction("User", "Index");
}
// 5. 创建一个获取cookie用户信息的方法方便调用
private int GetUserId()
{
//var userName = User.Identity.Name; //获取登录时存储的用户名称
var userId = User.FindFirst(ClaimTypes.Sid).Value; // 获取登录时存储的Id
if (string.IsNullOrEmpty(userId))
{
return 0;
}
else
{
return int.Parse(userId);
}
}
// 或者写一个测试Action
public JsonResult CheckLogin()
{
var userName = User.Identity.Name; //获取登录时存储的用户名称
var userId = User.FindFirst(ClaimTypes.Sid).Value; // 获取登录时存储的Id
return Json({UserId:userId,UserName:userName});
}
// 6. 以上是加密的方式如果直接写好像也是可以的
HttpContext.Response.Cookies.Append("Key", "Value");
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有