首页 > 编程语言 >ASP.NET Cookie身份认证

ASP.NET Cookie身份认证

时间:2024-10-21 17:00:47浏览次数:1  
标签:ASP AuthenticationScheme CookieAuthenticationDefaults Cookie context new NET opt

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;
}

官网

标签:ASP,AuthenticationScheme,CookieAuthenticationDefaults,Cookie,context,new,NET,opt
From: https://www.cnblogs.com/sugarwxx/p/18489841

相关文章

  • 位置、Cookie、缓存:华为鸿蒙 ArkWeb 数据管理全攻略
    本文旨在深入探讨华为鸿蒙HarmonyOSNext系统(截止目前API12)的技术细节,基于实际开发实践进行总结。主要作为技术分享与交流载体,难免错漏,欢迎各位同仁提出宝贵意见和问题,以便共同进步。本文为原创内容,任何形式的转载必须注明出处及原作者。引言ArkWeb是华为鸿蒙系统提......
  • 在K8S中,有家拥有分布式系统的跨国公司,拥有大量数据中心,虚拟机和许多从事各种任务的员
    对于拥有分布式系统的跨国公司,且该公司拥有大量数据中心、虚拟机以及众多从事各种任务的员工,采用Kubernetes(K8s)来管理所有任务是一种高效且灵活的方式。以下是一些建议,说明该公司如何以与Kubernetes一致的方式管理所有任务:1.利用Kubernetes的容器化特性容器化应用程序:将公司......
  • 【论文阅读】【IEEE TGARS】RRNet: Relational Reasoning Network WithParallel Multi
    引言任务:光学遥感显著目标检测-关系推理论文地址:RRNet:RelationalReasoningNetworkWithParallelMultiscaleAttentionforSalientObjectDetectioninOpticalRemoteSensingImages|IEEEJournals&Magazine|IEEEXplore代码地址:rmcong/RRNet_TGRS2021(g......
  • Raspberry Pi和Arduino哪个更适合DIY项目
    RaspberryPi和Arduino都是流行的DIY项目工具,但它们各有特点和适用范围。RaspberryPi是一种微型计算机,适合需要计算能力的项目,如媒体中心、游戏机或小型服务器。Arduino是一个微控制器板,适合控制简单的硬件项目,如自动化系统和传感器网络。选择哪个取决于项目需求:需要更多计算能......
  • .net core web api授权、鉴权、API保护
    前言本文整理asp.netcorewebAPI的授权、鉴权以及注册验证、API保护一系列常用技术手段。本文所有的实现代码可以参考:https://gitee.com/xiaoqingyao/web-app-identity.git用户管理授权和鉴权的前提是要有一个用户管理模块,.net提供一个现有的Identity组件,帮我们完成了大部......
  • 【K8S系列】Kubernetes Pod 状态详细介绍及异常状态解决方案
    在Kubernetes中,Pod是最小的可调度单元,负责运行一个或多个容器。Pod的状态能够反映其生命周期中的不同阶段,帮助用户了解当前的运行状况。本文将详细介绍KubernetesPod的各种状态及其可能的异常状态解决方案。一、Pod状态概览Pod的状态主要包括以下几种:PendingRu......
  • .NET Core SqlSugar
    概念:1.官方文档:https://www.donet5.com/Home/Doc?typeId=11802.在vsstudio中导包SqlSugarCore创建模型类:1.vsstudio2022中选择项目2.选择6.03.projram.csusingSqlSugar;varbuilder=WebApplication.CreateBuilder(args);//Addservicestothecontain......
  • Windows打开telnet功能
     同时按 Win+R  在输入框中输入cmd,点击确定按钮,点回车即可进入dos界面,输入telnet !!!  明显上面提示文字,不是内部或外部命令,也不是可运行的程序 !!!  1.鼠标移动到桌面栏底部右击鼠标--->2.任务栏设置--->3.主页--->4.搜索控制面板 --->5.网络和Internet -......
  • SDCN:《Structural Deep Clustering Network》
    代码:https://github.com/461054993/SDCN摘要聚类是数据分析中的一项基本任务。最近,主要从深度学习方法中获得灵感的深度聚类实现了最先进的性能,并引起了相当大的关注。当前的深度聚类方法通常借助深度学习强大的表示能力(例如自动编码器)来提高聚类结果,这表明学习有效的聚类表示......
  • C语言实现 网络通信 Network
    在现代计算机网络中,网络通信是不可或缺的一部分。本文将介绍如何使用C语言实现一个简单的网络通信库,涵盖TCP和UDP协议的基本功能。我们将通过一个示例代码库进行详细讲解,以便更好地理解网络编程的核心概念。项目结构本项目包含两个文件:network.h:头文件,定义了数据结构和函数......