Пример #1
0
        public AuthenticationTicket FetchTicket(HttpContext context, string name)
        {
            var cookie = context.Request.Cookies.FirstOrDefault(c => c.Key.StartsWith($"{_options.CookieName}-{name}"));

            if (cookie.Equals(default(KeyValuePair <string, string>)))
            {
                return(null);
            }

            return(_ticketDataFormat.Unprotect(cookie.Value));
        }
Пример #2
0
        public string GetUserIdFromTicket(string tiket)
        {
            var secureDataFormat = new TicketDataFormat(new MachineKeyProtector());
            AuthenticationTicket ticketContent = secureDataFormat.Unprotect(tiket);

            return(ticketContent.Identity.Name);
        }
Пример #3
0
        public IActionResult DecryptCookie()
        {
            ViewData["Message"] = "This is the decrypt page";
            var user = HttpContext.User;        //User will be set to the ClaimsPrincipal

            //Get the encrypted cookie value
            string cookieValue = HttpContext.Request.Cookies["gicoOAU"];
            IDataProtectionProvider provider = HttpContext.RequestServices.GetService <IDataProtectionProvider>();

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


            //Get the decrypted cookie as plain text
            UTF8Encoding specialUtf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);

            byte[] protectedBytes = Base64UrlTextEncoder.Decode(cookieValue);
            byte[] plainBytes     = dataProtector.Unprotect(protectedBytes);
            string plainText      = specialUtf8Encoding.GetString(plainBytes);


            //Get teh decrypted cookies as a Authentication Ticket
            TicketDataFormat     ticketDataFormat = new TicketDataFormat(dataProtector);
            AuthenticationTicket ticket           = ticketDataFormat.Unprotect(cookieValue);

            return(Content("111"));
        }
Пример #4
0
        public ActionResult Index()
        {
            var accessToken  = Request.Form["AccessToken"] ?? "";
            var refreshToken = Request.Form["RefreshToken"] ?? "";

            InitializeWebServerClient();

            if (string.IsNullOrEmpty(accessToken))
            {
                var authorizationState = _webServerClient.ProcessUserAuthorization(Request);
                if (authorizationState != null)
                {
                    var secureDataFormat        = new TicketDataFormat(new MachineKeyProtector());
                    AuthenticationTicket ticket = secureDataFormat.Unprotect(authorizationState.AccessToken);
                    var identity = ticket != null ? ticket.Identity : null;

                    // Add the cookie to the request to save it
                    HttpCookie cookie = new HttpCookie("CWAuthToken", authorizationState.AccessToken);
                    cookie.HttpOnly = true;
                    HttpContext.Response.Cookies.Add(cookie);
                    Response.Cookies.Add(cookie);

                    FormsAuthentication.SetAuthCookie(identity.Name, false);

                    return(RedirectToAction("index", "admin"));
                }

                Response.Cookies["CWAuthToken"].Expires = DateTime.Now.AddDays(-1);

                return(RedirectToAction("Index", "Home"));
            }

            return(View());
        }
Пример #5
0
        public static AuthenticationTicket GetCookieAuthenticationTicket(this HttpContext context, CookieAuthenticationOptions options)
        {
            try
            {
                //Get the encrypted cookie value
                string cookieValue = context.Request.Cookies[".AspNetCore.CookieAuth"];

                //Get a data protector to use with either approach
                var dataProtector = options.DataProtectionProvider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "CookieAuth", "v2");

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

                //Get the decrypted cookie as a Authentication Ticket
                TicketDataFormat     ticketDataFormat = new TicketDataFormat(dataProtector);
                AuthenticationTicket ticket           = ticketDataFormat.Unprotect(cookieValue);

                return(ticket);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Пример #6
0
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="httpContext">Http内容</param>
        /// <param name="cookieSchema">原加密的架构</param>
        /// <param name="CookieName">Cookie名称</param>
        /// <returns></returns>
        public static AuthenticationTicket Decrypt(HttpContext httpContext, string cookieSchema = "Identity.Application", string cookieName = ".AspNetCore.Identity.Application")
        {
            // Get the encrypted cookie value
            var CookieOpt     = httpContext.RequestServices.GetRequiredService <Microsoft.Extensions.Options.IOptionsMonitor <CookieAuthenticationOptions> >();
            var CookieOptVal  = CookieOpt?.CurrentValue;
            var cookieManager = CookieOptVal?.CookieManager ?? new ChunkingCookieManager();
            var cookie        = cookieManager.GetRequestCookie(httpContext, cookieName);

            if (!string.IsNullOrWhiteSpace(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");

                ////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     ticketDataFormat = new TicketDataFormat(dataProtector);
                AuthenticationTicket ticket           = ticketDataFormat.Unprotect(cookie);
                return(ticket);
            }
            else
            {
                return(null);
            }
        }
Пример #7
0
        public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {
            AuthenticationTicket ticket = _ticketDataFormat.Unprotect(securityToken);

            validatedToken = null;

            return(ticket?.Principal);
        }
Пример #8
0
        public String Test()
        {
            var accessToken             = "2wtL7hU4pHVdblFMBpS4l1Kwn6RP5_l_8pTp3PGS7tb4qetsCcuRNDzWmcM1oEpIMprjAgbEDB6XZ8WI4Y0yUEm-e39B3Eqnee2XD59Bs6x2S6L3mwHU7CyP3lzZpL8HxRiqBlwk2rY83DyB_AF-itWFHCOtPAjfW0tBvWh-gZFekmhpYS5aTF16J4bD4EWZ-lo-Ma-L3OC4ep1R1xhWsuAYWDY-j_7zOYeEmAtbPJDt8iDqBQ4okL5aCYZBbIh26Km1CIGSEccWygM3I_-lwQ";
            var secureDataFormat        = new TicketDataFormat(new MachineKeyProtector());
            AuthenticationTicket ticket = secureDataFormat.Unprotect(accessToken);

            return("");
        }
        public async Task <IActionResult> Index()
        {
            foreach (var scheme in await _schemes.GetRequestHandlerSchemesAsync())
            {
                var handler1 = await _handlers.GetHandlerAsync(HttpContext, scheme.Name) as IAuthenticationRequestHandler;

                if (handler1 != null && await handler1.HandleRequestAsync())
                {
                    return(View());
                }
            }
            var target = ResolveTarget(_options.CurrentValue.ForwardAuthenticate);

            var defaultAuthenticate = await _schemes.GetDefaultAuthenticateSchemeAsync();

            if (defaultAuthenticate != null)
            {
                var result = await HttpContext.AuthenticateAsync(defaultAuthenticate.Name);

                if (result?.Principal != null)
                {
                    HttpContext.User = result.Principal;
                }
            }

            string cookieValue = HttpContext.Request.Cookies[".Aspnetcore.Identity.Application"];

            var provider = _options.CurrentValue.DataProtectionProvider;
            //Get a data protector to use with either approach
            IDataProtector dataProtector = 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(cookieValue);
            byte[] plainBytes     = dataProtector.Unprotect(protectedBytes);
            string plainText      = specialUtf8Encoding.GetString(plainBytes);


            //Get the decrypted cookie as a Authentication Ticket
            TicketDataFormat     ticketDataFormat = new TicketDataFormat(dataProtector);
            AuthenticationTicket ticket           = ticketDataFormat.Unprotect(cookieValue);
            //CookieAuthenticationHandler a;
            //a.AuthenticateAsync()
            //var result = (await handler.AuthenticateAsync()) ?? AuthenticateResult.NoResult();
            //if (!result.Succeeded)
            //{
            //    return View();
            //}
            //var options = _options.CurrentValue;
            //var cookie = options.CookieManager.GetRequestCookie(HttpContext, options.Cookie.Name!);
            var b = await ReadCookieTicket();

            //var a = options.TicketDataFormat.Unprotect(cookie, GetTlsTokenBinding());
            return(View());
        }
        private AuthenticationTicket UnProtecedData(string protectedText)
        {
            if (_dataFormat == null)
            {
                _dataFormat = CreateDataFormat();
            }

            var ticket = _dataFormat.Unprotect(protectedText);

            return(ticket);
        }
Пример #11
0
        public ClaimsIdentity GetIdentityFromToken(string token)
        {
            var secureDataFormat = new TicketDataFormat(_dataProtector);
            var data             = secureDataFormat.Unprotect(token);

            if (null == data)
            {
                throw new UnauthorizedAccessException($"Cannot deserialize {token} data");
            }
            return(data.Identity);
        }
 public AuthenticationTicket DecodeToken(string token)
 {
     try
     {
         var value = token?.Replace(HelperConstants.BearerAuthenName, string.Empty);
         return(format.Unprotect(value?.Trim()));
     }
     catch (Exception)
     {
         return(null);
     }
 }
Пример #13
0
        public void Initialize(ITelemetry telemetry)
        {
            if (_httpContextAccessor.HttpContext == null)
            {
                return;
            }
            //if (!(telemetry is RequestTelemetry)) return;
            if (_httpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
            {
                var principal = _httpContextAccessor.HttpContext.User;
                var userId    = principal.FindFirst(ClaimTypes.NameIdentifier);
                telemetry.Context.User.Id = userId.Value;

                return;
            }

            // Get the encrypted cookie value
            var cookie = _httpContextAccessor.HttpContext.Request.Cookies[IdentityConstants.TwoFactorUserIdScheme];

            // Decrypt if found
            if (!string.IsNullOrEmpty(cookie))
            {
                try
                {
                    if (_httpContextAccessor.HttpContext.RequestServices == null)
                    {
                        return;
                    }
                    var dataProtector = _httpContextAccessor.HttpContext.RequestServices.GetDataProtector(
                        "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware",
                        IdentityConstants.TwoFactorUserIdScheme, "v2");
                    ////https://github.com/aspnet/Security/blob/master/src/Microsoft.AspNetCore.Authentication.Cookies/PostConfigureCookieAuthenticationOptions.cs
                    //var dataProtector = _dataProtectProvider.CreateProtector(
                    //    "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware",
                    //    IdentityConstants.TwoFactorUserIdScheme, "v2");

                    var ticketDataFormat = new TicketDataFormat(dataProtector);
                    var ticket           = ticketDataFormat.Unprotect(cookie);
                    var val = ticket?.Principal?.Claims?.FirstOrDefault(f => f.Type == ClaimTypes.Name);
                    if (val != null)
                    {
                        telemetry.Context.User.Id = val.Value;
                        //telemetry.Context.Session.Id = val.Value;
                    }
                }
                catch (Exception)
                {
                    //_logger.Value.TrackException(ex);
                    // ignored
                }
            }
        }
        private static AuthenticationTicket GetAuthenticationKeyTicket()
        {
            AuthenticationTicket ticket = null;

            var ctx = HttpContext.Current.Request;
            if (ctx.Cookies != null && ctx.Cookies[".AspNet.Cookies"] != null)
            {
                var cookie = ctx.Cookies[".AspNet.Cookies"];
                var secureDataFormat = new TicketDataFormat(new MachineKeyProtector());
                ticket = secureDataFormat.Unprotect(cookie.Value);
            }
            return ticket;
        }
Пример #15
0
        private AuthenticationTicket GetAuthenticationKeyTicket()
        {
            AuthenticationTicket ticket  = null;
            HttpCookieCollection cookies = _requestBase?.Cookies ?? HttpContext.Current.Request.Cookies;

            if (cookies[AuthenticationCookieKey] != null)
            {
                HttpCookie cookie = cookies[AuthenticationCookieKey];
                ticket = TicketDataFormat.Unprotect(cookie.Value);
            }

            return(ticket);
        }
        public static System.Security.Claims.ClaimsIdentity GetUserIdentty()
        {
            HttpCookie authCookie = HttpContext.Current.Request.Cookies.Get("CWAuthToken");

            if (authCookie != null)
            {
                var secureDataFormat        = new TicketDataFormat(new MachineKeyProtector());
                AuthenticationTicket ticket = secureDataFormat.Unprotect(authCookie.Value);
                var identity = ticket != null ? ticket.Identity : null;
                return(identity);
            }

            return(null);
        }
Пример #17
0
        private static AuthenticationTicket GetAuthenticationKeyTicket()
        {
            AuthenticationTicket ticket = null;

            var ctx = HttpContext.Current.Request;

            if (ctx.Cookies != null && ctx.Cookies[".AspNet.Cookies"] != null)
            {
                var cookie           = ctx.Cookies[".AspNet.Cookies"];
                var secureDataFormat = new TicketDataFormat(new MachineKeyProtector());
                ticket = secureDataFormat.Unprotect(cookie.Value);
            }
            return(ticket);
        }
Пример #18
0
        public string GetUserIdFromTicket(string tiket)
        {
            var secureDataFormat = new TicketDataFormat(new MachineKeyProtector());
            AuthenticationTicket ticketContent = secureDataFormat.Unprotect(tiket);

            if (ticketContent != null)
            {
                Claim claim = ticketContent.Identity.FindFirst(t => t.Type == "sub");

                return(claim.Value);
            }

            return(string.Empty);
        }
Пример #19
0
        public Task <AuthenticationTicket> RetrieveAsync(string key)
        {
            AuthenticationTicket ticket = null;

            using (SqlAuthSessionStoreContext store = new SqlAuthSessionStoreContext(_connectionString))
            {
                AuthSessionEntry entry = store.Entries.FirstOrDefault(a => a.Key == key);
                if (entry != null)
                {
                    ticket = _formatter.Unprotect(entry.TicketString);
                }

                return(Task.FromResult(ticket));
            }
        }
        private IEnumerable <Claim> GetClaimFromCookie(HttpContext httpContext, string cookieName, string cookieSchema)
        {
            IOptionsMonitor <CookieAuthenticationOptions> opt = httpContext.RequestServices.GetRequiredService <IOptionsMonitor <CookieAuthenticationOptions> >();
            string cookie = opt.CurrentValue.CookieManager.GetRequestCookie(httpContext, cookieName);

            if (!string.IsNullOrEmpty(cookie))
            {
                IDataProtector       dataProtector    = opt.CurrentValue.DataProtectionProvider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", cookieSchema, "v2");
                TicketDataFormat     ticketDataFormat = new TicketDataFormat(dataProtector);
                AuthenticationTicket ticket           = ticketDataFormat.Unprotect(cookie);

                return(ticket.Principal.Claims);
            }
            return(null);
        }
Пример #21
0
        /// <summary>
        /// <![CDATA[配置简化授权模式]]>
        /// </summary>
        /// <param name="app"></param>
        public void Configuration(IAppBuilder app)
        {
            // 有关如何配置应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkID=316888
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
            {
                AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
                AuthenticationType = "Brearer",
                Description        = new Microsoft.Owin.Security.AuthenticationDescription()
                {
                },
                Provider = new OAuthBearerAuthenticationProvider()
                {
                    //http头中携带access_token时,
                    OnRequestToken = (e) =>
                    {
                        //解密令牌,生成身份票据
                        if (string.IsNullOrEmpty(e.Token) == false)
                        {
                            IDataProtector protector          = app.CreateDataProtector(typeof(OAuthAuthorizationServerMiddleware).Namespace, "Access_Token", "v1");
                            TicketDataFormat ticketDataFormat = new TicketDataFormat(protector);
                            var ticket     = ticketDataFormat.Unprotect(e.Token);
                            e.Request.User = new ClaimsPrincipal(ticket.Identity);
                        }
                        return(Task.FromResult(0));
                    },
                    OnValidateIdentity = (e) =>
                    {
                        if (e.Ticket != null)
                        {
                            e.Validated();
                        }
                        return(Task.FromResult(0));
                    }
                }
            });

            //认证服务中间件
            app.UseOAuthAuthorizationServer(new Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp     = true,
                AuthenticationMode    = Microsoft.Owin.Security.AuthenticationMode.Active,
                AuthenticationType    = "Bearer",
                AuthorizeEndpointPath = new PathString("/oauth2/Authorize"),
                TokenEndpointPath     = new PathString("/oauth2/Token"),
                Provider = new ImpicitAuthorizationServerProvider(),
                AccessTokenExpireTimeSpan = new TimeSpan(2, 0, 0),
            });
        }
Пример #22
0
        public ActionResult Index()
        {
            var cookie = System.Web.HttpContext.Current.Request.Cookies.Get(".AspNet.ApplicationCookie");
            var ticket = cookie.Value;

            //Handle encoding
            ticket = ticket.Replace('-', '+').Replace('_', '/');
            var padding = 3 - ((ticket.Length + 3) % 4);

            if (padding != 0)
            {
                ticket = ticket + new string('=', padding);
            }

            var machineKeyProtector = new MachineKeyProtector();
            var ticketData          = new TicketDataFormat(machineKeyProtector);


            //Set the purpose for decrypting the cookie based ticket
            machineKeyProtector.Purpose = new string[]
            {
                typeof(CookieAuthenticationMiddleware).FullName,
                "ApplicationCookie",
                "v1"
            };
            var decryptedTicket = ticketData.Unprotect(ticket);

            //Change the purpose for creating an encrypted bearer token
            machineKeyProtector.Purpose = new string[]
            {
                typeof(OAuthAuthorizationServerMiddleware).Namespace,
                "Access_Token",
                "v1"
            };
            var encryptedTicket = ticketData.Protect(decryptedTicket);

            string bearerToken = $"Bearer {encryptedTicket}";

            var client = new HttpClient();

            client.BaseAddress = new Uri("http://localhost:58719/");
            client.DefaultRequestHeaders.Add("Authorization", bearerToken);
            var result = client.GetAsync("/api/ResourceData").Result.Content.ReadAsStringAsync().Result;

            ViewBag.ResultData  = result;
            ViewBag.BearerToken = bearerToken;
            return(View());
        }
Пример #23
0
        // OWINで生成したアクセストークンを復号する
        // https://long2know.com/2015/05/decrypting-owin-authentication-ticket/
        public bool Decrypt(string accessToken)
        {
            IDataProtector protector = null;

            if (this.Type == TokenType.AccessToken)
            {
                protector = new AccessTokenMachineKeyProtector();
            }
            else if (this.Type == TokenType.RefreshToken)
            {
                protector = new RefreshTokenMachineKeyProtector();
            }

            // Decrypt
            var secureDataFormat        = new TicketDataFormat(protector);
            AuthenticationTicket ticket = secureDataFormat.Unprotect(accessToken);

            if (ticket == null)
            {
                return(false);
            }

            {
                var jstTimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
                DateTimeIssued  = System.TimeZoneInfo.ConvertTimeFromUtc(ticket.Properties.IssuedUtc.Value.DateTime, jstTimeZoneInfo);
                DateTimeExpires = System.TimeZoneInfo.ConvertTimeFromUtc(ticket.Properties.ExpiresUtc.Value.DateTime, jstTimeZoneInfo);
            }

            // get identity
            var identity      = ticket.Identity as ClaimsIdentity;
            var roleClaims    = identity.Claims.Where(x => x.Type == ClaimsIdentity.DefaultRoleClaimType).Select(x => x.Value).ToList();
            var nonRoleClaims = identity.Claims.Where(x => x.Type != ClaimsIdentity.DefaultRoleClaimType).Select(x => new { Type = x.Type, Value = x.Value }).ToList();

            IdentityName = identity.Name;
            Roles        = roleClaims;

            Claims = new List <Claim>();
            foreach (var c in nonRoleClaims)
            {
                var setc = new TokenDecrypt.Claim();
                setc.Type  = c.Type;
                setc.Value = c.Value;
                Claims.Add(setc);
            }

            return(true);
        }
Пример #24
0
 internal static AuthenticationTicket ReadAuthCookie(HttpContext context, string encryptedCookie, ILogger logger)
 {
     try
     {
         var opt              = context.RequestServices.GetRequiredService <IOptionsMonitor <CookieAuthenticationOptions> >();
         var dataProtector    = opt.CurrentValue.DataProtectionProvider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", CookieAuthenticationDefaults.AuthenticationScheme, "v2");
         var ticketDataFormat = new TicketDataFormat(dataProtector);
         var ticket           = ticketDataFormat.Unprotect(encryptedCookie);
         return(ticket);
     }
     catch (Exception ex)
     {
         // Log the exception, but do not leak other information
         logger.ErrorUnprotectingSessionCookie(ex);
         return(null);
     }
 }
Пример #25
0
        public override AuthenticationTicket Unprotect(string protectedText)
        {
            var result = default(AuthenticationTicket);

            try
            {
                result = base.Unprotect(protectedText);
            }
            catch { }

            if (result == null)
            {
                var secureDataFormat = new TicketDataFormat(new MachineKeyProtector());
                result = secureDataFormat.Unprotect(protectedText);
            }
            return(result);
        }
Пример #26
0
        // https://long2know.com/2016/05/extracting-bearer-token-from-owin-cookie/
        public static AuthenticationTicket GetAuthenticationTicketFromCookie(HttpContextBase context)
        {
            var cookie = context.Request.Cookies.Get("WsFederationPoC");
            var ticket = cookie.Value;

            // Deal with URL encoding
            ticket = ticket.Replace('-', '+').Replace('_', '/');
            var padding = 3 - (ticket.Length + 3) % 4;

            if (padding != 0)
            {
                ticket = ticket + new string('=', padding);
            }
            var secureDataFormat = new TicketDataFormat(new MachineKeyProtector("cookie"));

            return(secureDataFormat.Unprotect(ticket));
        }
Пример #27
0
        private static void ReplacePrincipal(object sender, EventArgs args)
        {
            var cookie = HttpContext.Current.Request.Cookies[AuthService.CookiesIdentifier];

            if (cookie == null)
            {
                return;
            }

            var ticketFormat = new TicketDataFormat(new DataProtector(AuthService.ProtectionPurpose));
            var ticket       = ticketFormat.Unprotect(cookie.Value);

            if (ticket != null)
            {
                var principal = new ClaimsPrincipal(ticket.Identity);
                HttpContext.Current.User = principal;
            }
        }
        public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request)
        {
            var dataProtectionProvider = new DpapiDataProtectionProvider();
            var secureDataFormat       = new TicketDataFormat(dataProtectionProvider.Create());
            // authenticate by using bearer token in query string
            var token  = request.QueryString.Get(OAuthDefaults.AuthenticationType);
            var ticket = secureDataFormat.Unprotect(token);

            if (ticket != null && ticket.Identity != null && ticket.Identity.IsAuthenticated)
            {
                // set the authenticated user principal into environment so that it can be used in the future
                request.Environment["server.User"] = new ClaimsPrincipal(ticket.Identity);
                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #29
0
        public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request)
        {
            var authorizeHubConnection = true;
            //bool authorizeHubConnection = base.AuthorizeHubConnection(hubDescriptor, request);
            DpapiDataProtectionProvider dataProtectionProvider = new DpapiDataProtectionProvider();
            IDataProtector protector = dataProtectionProvider.Create("ASP.NET Identity");
            DataProtectorTokenProvider <ApplicationUser> dataProtectorTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(protector);
            IDataProtector dataProtector = dataProtectionProvider.Create(_purpose);

            TicketDataFormat     secureDataFormat = new TicketDataFormat(dataProtector);
            string               token            = request.QueryString.Get(OAuthDefaults.AuthenticationType);
            AuthenticationTicket ticket           = secureDataFormat.Unprotect(token);

            if (authorizeHubConnection && ticket != null && ticket.Identity != null && ticket.Identity.IsAuthenticated)
            {
                request.Environment["server.User"] = new ClaimsPrincipal(ticket.Identity);
            }
            return(authorizeHubConnection);
        }
Пример #30
0
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            if (this.Context == null)
            {
                return(AuthenticateResult.Fail("context is null"));
            }
            // 获取token
            var token = this.Context.Request.Query[Options.TokenQueryKey].FirstOrDefault();

            if (string.IsNullOrEmpty(token))
            {
                await this.Context.Response.WriteAsync("toke is null");

                return(AuthenticateResult.NoResult());
            }

            var unprotectToke = _dataformat.Unprotect(token);

            if (unprotectToke == null)
            {
                //unprotectToke.Principal.Identity.Name;
                await this.Context.Response.WriteAsync("toke data is null");

                return(AuthenticateResult.NoResult());
            }

            if (unprotectToke.Properties?.ExpiresUtc.HasValue == true)
            {
                if (unprotectToke.Properties.ExpiresUtc < base.Clock.UtcNow)
                {
                    await this.Context.Response.WriteAsync("Ticket Expire");

                    return(AuthenticateResult.Fail("Ticket Expire"));
                }
            }

            if (unprotectToke.Principal == null)
            {
                return(AuthenticateResult.Fail("no principal"));
            }
            return(AuthenticateResult.Success(unprotectToke));
        }
Пример #31
0
        public string DecryptClaim()
        {
            // Get the encrypted cookie value
            var opt    = httpContextAccessor.HttpContext.RequestServices.GetRequiredService <IOptionsMonitor <Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationOptions> >();
            var cookie = opt.CurrentValue.CookieManager.GetRequestCookie(httpContextAccessor.HttpContext, ".AspNetCore.Cookies");

            // Decrypt if found
            if (!string.IsNullOrEmpty(cookie))
            {
                var dataProtector = opt.CurrentValue.DataProtectionProvider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme, "v2");

                var ticketDataFormat = new TicketDataFormat(dataProtector);
                var ticket           = ticketDataFormat.Unprotect(cookie);
                var claims           = ticket.Principal.Claims;
                var list             = claims.ToList();

                return(list[0].Value);
            }
            return(null);
        }