ASP.NET Cookie身份认证

1.添加Cookie身份验证方案
services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; option.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.Cookie.HttpOnly = true;//获取或设置一个值,该值指示浏览器是否仅通过HTTP访问Cookie(即,不允许通过客户端脚本访问)。默认值为 true,这是一个安全特性,用于防止跨站脚本攻击(XSS) options.ExpireTimeSpan = TimeSpan.FromSeconds(60);//表示Cookies中的token存留的过期时间 //options.Cookie.MaxAge = TimeSpan.FromSeconds(60);//表示Cookie存留的最大时间,当ExpireTimeSpan与MaxAge同时存在时以MaxAge时间为准 options.LoginPath = "/Account/Login";//获取或设置当用户需要登录时应重定向到的路径 options.AccessDeniedPath = "/Account/AccessDenied";//获取或设置当用户尝试访问他们未经授权的资源时应重定向到的路径。 options.SlidingExpiration = true;//该值指示是否应在每次请求时重置身份验证Cookie的过期时间。如果设置为 true,发出了请求并且超过了一半的超时时间间隔,则滑动过期会重置有效身份验证 cookie 的过期时间。 如果 cookie 过期,用户必须重新进行身份验证 //options.Cookie.Expiration= TimeSpan.FromSeconds(60); var originRedirectToLogin = options.Events.OnRedirectToLogin;//当用户尝试访问需要身份验证的资源,但尚未登录时触发 options.Events.OnRedirectToLogin = context => { var originUri = new Uri(context.RedirectUri); context.RedirectUri = originUri.PathAndQuery; //修改asp.net 重定向的时候去掉域名部分 return originRedirectToLogin(context); };

 

2.启用认证授权

//认证
app.UseAuthentication();
//授权,授权必须是基于认证之后
app.UseAuthorization();

 

3.创建身份验证Cookie

 var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, user.Email),
            new Claim("FullName", user.FullName),
new Claim("Account", user.Account),
new Claim(ClaimTypes.Role, "Administrator"), }; var claimsIdentity = new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new AuthenticationProperties { //AllowRefresh = <bool>, // Refreshing the authentication session should be allowed. //ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10), // The time at which the authentication ticket expires. A // value set here overrides the ExpireTimeSpan option of // CookieAuthenticationOptions set with AddCookie. //IsPersistent = true, // Whether the authentication session is persisted across // multiple requests. When used with cookies, controls // whether the cookie's lifetime is absolute (matching the // lifetime of the authentication ticket) or session-based. //IssuedUtc = <DateTimeOffset>, // The time at which the authentication ticket was issued. //RedirectUri = <string> // The full path or absolute URI to be used as an http // redirect response value. }; //将凭证写入Cookie中(存放于浏览器中)加密保存 await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);

 

4.自定义Cookie认证事件

ValidatePrincipal事件不满足需求时,可派生自CookieAuthenticationEvents的类中编写具有以下签名的方法

ValidatePrincipal(CookieValidatePrincipalContext)

派生示例例如

验证用户是否存在数据库中

public class CustomCookieAuthenticationEvents: CookieAuthenticationEvents
{
    private IUserService _userService;

    public CustomCookieAuthenticationEvents(IUserService userService)
    {
        _userService = userService;
    }
    public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
    {
        var userPrincipal = context.Principal;

        var account = (from c in userPrincipal.Claims
                           where c.Type == "Account"
                           select c.Value).FirstOrDefault();

        if (string.IsNullOrEmpty(account) ||
             !await _userService.CheckUserExist(account))
        {
            context.RejectPrincipal();

            await context.HttpContext.SignOutAsync(
                CookieAuthenticationDefaults.AuthenticationScheme);
        }
    }
}

注册事件

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.EventsType = typeof(CustomCookieAuthenticationEvents);
    });

builder.Services.AddScoped<CustomCookieAuthenticationEvents>();

 

5.注销

public async Task OnGetAsync(string returnUrl = null)
{
    if (!string.IsNullOrEmpty(ErrorMessage))
    {
        ModelState.AddModelError(string.Empty, ErrorMessage);
    }

    // Clear the existing external cookie
    await HttpContext.SignOutAsync(
        CookieAuthenticationDefaults.AuthenticationScheme);

    ReturnUrl = returnUrl;
}

官网

posted @ 2024-10-21 17:05  流年sugar  阅读(48)  评论(0编辑  收藏  举报