.Net Core 2.2 解密 Cookie Authentication-Token

参考:https://stackoverflow.com/questions/42842511/how-to-manually-decrypt-an-asp-net-core-authentication-cookie/42857830#42857830

//设置Indetity

services.AddIdentity<ApplicationUser, IdentityRole>(IdentityOpts =>
            {
                // Password settings.
                IdentityOpts.Password.RequireDigit = true;
                IdentityOpts.Password.RequireLowercase = true;
                IdentityOpts.Password.RequireNonAlphanumeric = true;
                IdentityOpts.Password.RequireUppercase = true;
                IdentityOpts.Password.RequiredLength = 6;
                IdentityOpts.Password.RequiredUniqueChars = 1;

                // Lockout settings.
                IdentityOpts.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
                IdentityOpts.Lockout.MaxFailedAccessAttempts = 5;
                IdentityOpts.Lockout.AllowedForNewUsers = true;

                // User settings.
                IdentityOpts.User.AllowedUserNameCharacters =
                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
                IdentityOpts.User.RequireUniqueEmail = false;

            }).AddEntityFrameworkStores<ApplicationDbContext>()
              .AddDefaultTokenProviders();//默认Scheme Identity.Application

//设置Authentication

services.AddAuthentication(AuthOpts =>
            {
                AuthOpts.DefaultScheme = "MichaelAuth";
                AuthOpts.DefaultSignInScheme = "MichaelAuth";
                //AuthOpts.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                //AuthOpts.DefaultAuthenticateScheme = Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme;

                //AuthOpts.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                //AuthOpts.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                //AuthOpts.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            }).AddCookie("MichaelAuth", CookieOpts => //增加Cookie Authentication
             {
                 CookieOpts.Cookie.Name = "MichaelAuth.NetCoreApp";
                 CookieOpts.SlidingExpiration = true;
                 CookieOpts.LoginPath = "/Account/Login";
                 CookieOpts.ReturnUrlParameter = "RetMichael";
                 CookieOpts.ExpireTimeSpan = TimeSpan.FromSeconds(30);
                 自定义MachineKey或者其他密钥
                 //CookieOpts.DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"C:\temp-keys\"));
                 CookieOpts.Events = new CookieAuthenticationEvents
                 {
                    OnValidatePrincipal = context => //验证 票据Action
                    {
                        var Claims_Identity = context.HttpContext.User.Identity as System.Security.Claims.ClaimsIdentity;
                        Console.WriteLine("{0} - {1}: {2}", DateTime.Now,
                          "OnValidatePrincipal", context.Principal.Identity.Name);
                        return Task.CompletedTask;
                    }
                };
             });
            //设置Identity.Application-Cookie过期时间
            services.ConfigureApplicationCookie(options =>
            {
                options.ExpireTimeSpan = TimeSpan.FromSeconds(30);
            });

//解密票据
        private IEnumerable<System.Security.Claims.Claim> GetClaimFromCookie(Microsoft.AspNetCore.Http.HttpContext httpContext, string cookieSchema="Identity.Application")
        {
            // Get the encrypted cookie value
            var CookieOpt = httpContext.RequestServices.GetRequiredService<Microsoft.Extensions.Options.IOptionsMonitor<CookieAuthenticationOptions>>();
            var CookieOptVal = CookieOpt.CurrentValue;
            var cookieName = "MichaelAuth.NetCoreApp";// CookieOptVal.Cookie.Name;
            var AuthSchemes = HttpContext.Authentication.GetAuthenticationSchemes();
            var cookie = CookieOptVal.CookieManager.GetRequestCookie(httpContext, cookieName);

            // Decrypt if found
            if (!string.IsNullOrEmpty(cookie))
            {
                自定义MachineKey或者其他密钥
                //var provider = DataProtectionProvider.Create(new DirectoryInfo(@"C:\temp-keys\"));
                var provider = CookieOptVal.DataProtectionProvider;
                var dataProtector = provider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", cookieSchema, "v2");

                var ticketDataFormat = new TicketDataFormat(dataProtector);
                var ticket = ticketDataFormat.Unprotect(cookie);

                #region MyRegion

                var cookieManager = new ChunkingCookieManager();

                var dataProtector0 = provider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Identity.Application", "v2");

                Get the decrypted cookie as plain text
                //UTF8Encoding specialUtf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
                //byte[] protectedBytes = Base64UrlTextEncoder.Decode(cookie);
                //byte[] plainBytes = dataProtector.Unprotect(protectedBytes);
                //string plainText = specialUtf8Encoding.GetString(plainBytes);

                //Get teh decrypted cookies as a Authentication Ticket
                TicketDataFormat ticketDataFormat0 = new TicketDataFormat(dataProtector0);
                AuthenticationTicket ticket0 = ticketDataFormat0.Unprotect(cookie);

                #endregion

                #region MyRegion

                //Get a data protector to use with either approach
                var dataProtector1 = provider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Identity.Application", "v2");

                Get the decrypted cookie as plain text
                //UTF8Encoding specialUtf8Encoding1 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
                //byte[] protectedBytes1 = Base64UrlTextEncoder.Decode(cookie);
                //byte[] plainBytes1 = dataProtector.Unprotect(protectedBytes1);
                //string plainText1 = specialUtf8Encoding.GetString(plainBytes1);

                //Get the decrypted cookie as a Authentication Ticket
                TicketDataFormat ticketDataFormat1 = new TicketDataFormat(dataProtector1);
                AuthenticationTicket ticket1 = ticketDataFormat1.Unprotect(CookieOptVal.CookieManager.GetRequestCookie(httpContext, ".AspNetCore.Identity.Application"));

                #endregion

                #region MyRegion

                //Get a data protector to use with either approach
                var dataProtector2 = provider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware");
                //Get the decrypted cookie as a Authentication Ticket
                TicketDataFormat ticketDataFormat2 = new TicketDataFormat(dataProtector2);
                AuthenticationTicket ticket2 = ticketDataFormat2.Unprotect(cookie);

                #endregion
                return ticket?.Principal.Claims;
            }
            return null;
        }
 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值