示例#1
0
        //public CustomPrincipal(string firstName, string lastName, string badge, string cardNumber, string sessionId) : base(new GenericIdentity(badge))
        //{
        //    Logger.WriteDebug("SessionId:" + sessionId);
        //    var hasAccess = false;
        //    var key = $"{firstName}_{lastName}_{badge}_{cardNumber}_{sessionId}";
        //    if (Cache.Get(key) is bool cacheFound)
        //        hasAccess = cacheFound;
        //    else
        //    {
        //        hasAccess = AsyncHelpers.RunSync(async () =>
        //        {
        //            using (var service = new OperatorHandler())
        //            {
        //                return await service.IsValidSessionAsync(firstName, lastName, badge, sessionId);
        //            }
        //        });
        //        Cache.Add(key, hasAccess, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
        //    }



        //    if (!hasAccess)
        //        throw new UnauthorizedAccessException();

        //}
        public CustomPrincipal(string badge, string deviceGuid, string sessionId) : base(new GenericIdentity(badge))
        {
            Logger.WriteDebug($"Badge: {badge}, SessionId: {sessionId}, deviceGuid: {deviceGuid}");
            var hasAccess = false;
            var jobTitle  = "";
            var user      = "";
            var key       = $"{badge}_{sessionId}";

            if (Cache.Get(key) is Tuple <bool, string, string> cacheFound)
            {
                hasAccess = cacheFound.Item1;
                jobTitle  = cacheFound.Item2;
                user      = cacheFound.Item3;
            }
            else
            {
                hasAccess = AsyncHelpers.RunSync(async() =>
                {
                    using (var service = new OperatorHandler())
                    {
                        var result = await service.IsValidSessionAsync(badge, deviceGuid, sessionId);
                        jobTitle   = result.Item2;
                        user       = result.Item3;
                        return(result.Item1);
                    }
                });
                Cache.Add(key, new Tuple <bool, string, string>(hasAccess, jobTitle, user), null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
            }


            if (!hasAccess)
            {
                throw new UnauthorizedAccessException();
            }


            var claims = new List <Claim>();

            Identity.AddClaim(new Claim("JobTitle", jobTitle));
            Identity.AddClaim(new Claim("User", user));
        }
        public override void OnAuthorization(HttpActionContext filterContext)
        {
            if (SkipAuthorization(filterContext))
            {
                return;
            }


            const string key1 = "sessionId";
            const string key2 = "badge";
            const string key3 = "deviceGuid";
            bool         hasAccess;
            string       sessionId  = GetHeaderValue(filterContext, key1);
            string       badge      = GetHeaderValue(filterContext, key2);
            string       deviceGuid = GetHeaderValue(filterContext, key3);

            hasAccess = AsyncHelpers.RunSync(async() =>
            {
                using (var service = new OperatorHandler())
                {
                    var result = await service.IsValidSessionAsync(badge, deviceGuid, sessionId);
                    return(result?.Item1 ?? false);
                }
            });



            //_logger.Debug("SessionId:" + sessionId);
            //if (!string.IsNullOrEmpty(sessionId))
            //{
            //    try
            //    {
            //        var ticket = FormsAuthentication.Decrypt(sessionId);
            //        if (ticket != null)
            //        {
            //            _logger.Debug("tikcet is not null! " + ticket.UserData);
            //            var userData = ticket.UserData;
            //            if (!string.IsNullOrWhiteSpace(userData))
            //            {
            //                _logger.Debug("User data object is created.");
            //                var user = JsonConvert.DeserializeObject<SecurityUserInfo>(userData);
            //                _logger.Debug("User data DeserializeObject successfull!");
            //                if (user != null)
            //                {
            //                    _logger.Debug("User data user is not null!");
            //                    using (var service = new OperatorHandler())
            //                    {
            //                        hasAccess = service.IsValidSession(user.Badge, ticket.Name,sessionId);
            //                        _logger.Debug("has Access:" + hasAccess);
            //                    }
            //                }
            //            }
            //        }

            //    }
            //    catch (Exception ex)
            //    {
            //        _logger.Error("Error on OnAuthorization", ex);

            //        throw new FriendlyException(FriendlyExceptionType.AccessDenied);
            //    }
            //}


            //if (!string.IsNullOrEmpty(Token) || (Tokens != null && Tokens.Length > 0))
            //{
            //    if (Tokens == null || Tokens.Length == 0)
            //        hasAccess = AuthorizeHelper.HasAccess(Token);
            //    else
            //    {
            //        var arr = new List<string>();
            //        if (Tokens != null)
            //            arr.AddRange(Tokens);
            //        if (!string.IsNullOrEmpty(Token))
            //            arr.Add(Token);
            //        foreach (var token in arr)
            //        {
            //            hasAccess = AuthorizeHelper.HasAccess(token);
            //            if (hasAccess)
            //                break;
            //        }
            //    }
            //}

            //if (!string.IsNullOrEmpty(Tokens))
            //{
            //    string[] tokens;
            //    if (Tokens.Contains(';'))
            //        tokens = Tokens.Split(';');
            //    else
            //        tokens = Tokens.Split(',');
            //    foreach (var token in tokens)
            //    {
            //        hasAccess = AuthorizeHelper.HasAccess(token);
            //        if (hasAccess)
            //            break;
            //    }
            //}
            if (!hasAccess)
            {
                throw new FriendlyException(FriendlyExceptionType.AccessDenied);
            }
        }