public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (IsAllowAnonymous(actionContext))
            {
                return;
            }
            var token = GetJwtToken(actionContext);

            if (string.IsNullOrWhiteSpace(token))
            {
                HandleUnauthenticatedRequest(actionContext, "Token为空。");
            }
            var jwtInfo = JwtHelper.Decode <IDictionary <string, object> >(token, _secret);

            if (jwtInfo.IsSucceed)
            {
                if (IsAuthenticated(jwtInfo.Payload))
                {
                    base.OnAuthorization(actionContext);
                }
            }
            else
            {
                HandleUnauthenticatedRequest(actionContext, jwtInfo.Msg);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// 获取登录信息
        /// </summary>
        /// <remarks>
        /// 获取header或者参数携带的x-token参数
        /// </remarks>
        /// <returns></returns>
        public UserApiTokenPayload GetUserPayloadByToken()
        {
            if (_cachePaload != null)
            {
                return(_cachePaload);
            }
            var token = _httpContextAccessor.HttpContext.Request.Headers["X-Token"];

            //header或者query带有x-token参数
            token = string.IsNullOrEmpty(token) ? _httpContextAccessor.HttpContext.Request.Query["x-token"] : token;
            if (string.IsNullOrEmpty(token))
            {
                return(null);
            }
            _cachePaload = JwtHelper.Decode <UserApiTokenPayload>(token, _api_key_token);
            return(_cachePaload);
        }
Esempio n. 3
0
        public T GetController <T>(string token = null) where T : ControllerBase
        {
            var controller = GetScopedService <T>();

            controller.ControllerContext.HttpContext = new TestHttpContext();
            if (token != null)
            {
                var session    = GetScopedService <SessionDto>();
                var sessionDto = JwtHelper.Decode <SessionDto>(token);

                session.Username       = sessionDto.Username;
                session.ExpirationTime = sessionDto.ExpirationTime;
                session.Password       = sessionDto.Password;
                session.SessionId      = sessionDto.SessionId;
                session.UserId         = sessionDto.UserId;
            }

            return(controller);
        }
Esempio n. 4
0
        public IActionResult LogOut()
        {
            string jwt = this.HttpContext.Request.Cookies["auth"];

            if (string.IsNullOrEmpty(jwt))
            {
                return(Redirect("/"));
            }

            var payloadString = JwtHelper.Decode(jwt);

            if (string.IsNullOrEmpty(payloadString))
            {
                return(Redirect("/"));
            }

            var payLoad = JsonConvert.DeserializeObject <Dictionary <string, string> >(payloadString);
            var token   = payLoad["token"];

            if (string.IsNullOrEmpty(token))
            {
                return(Redirect("/"));
            }

            var loginSession = BaseDBRepository.UserLoginTokenRepository.GetAll()
                               .Include(x => x.User)
                               .FirstOrDefault(x => x.Token == token);

            if (loginSession == null)
            {
                return(Redirect("/"));
            }

            this.BaseDBRepository.UserLoginTokenRepository.Delete(loginSession);
            this.BaseDBRepository.Commit();
            this.Response.Cookies.Delete("auth");
            return(Redirect("/"));
        }
Esempio n. 5
0
        private void PopulateToken(AuthTokenDto authToken)
        {
            if (cbSaml.Checked)
            {
                var bytes = Convert.FromBase64String(authToken.Token.AccessToken);
                var value = System.Text.Encoding.Default.GetString(bytes);
                txtSamlToken.Text = value;
            }
            else
            {
                try
                {
                    txtIdToken.Text = JwtHelper.Decode(authToken.Token.IdToken);
                }
                catch
                {
                    txtIdToken.Text = authToken.Token.IdToken;
                }

                try
                {
                    txtAccessToken.Text = JwtHelper.Decode(authToken.Token.AccessToken);
                }
                catch
                {
                    txtAccessToken.Text = authToken.Token.AccessToken;
                }

                try
                {
                    txtRefreshToken.Text = JwtHelper.Decode(authToken.Token.RefreshToken);
                }
                catch
                {
                    txtRefreshToken.Text = authToken.Token.RefreshToken;
                }
            }
        }
 private void PopulateToken(AuthTokenDto authToken)
 {
     TxtIDTokenString.StringValue      = JwtHelper.Decode(authToken.Token.IdToken);
     TxtAccessTokenString.StringValue  = JwtHelper.Decode(authToken.Token.AccessToken);
     TxtRefreshTokenString.StringValue = JwtHelper.Decode(authToken.Token.RefreshToken);
 }
Esempio n. 7
0
        public Task HandleAsync(AuthorizationHandlerContext context)
        {
            var mvcContext = context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext;

            if (mvcContext == null)
            {
                return(Task.CompletedTask);
            }

            string jwt = mvcContext.HttpContext.Request.Cookies["auth"];

            if (string.IsNullOrEmpty(jwt) || jwt == "null")
            {
                return(Task.CompletedTask);
            }

            var payloadString = JwtHelper.Decode(jwt);

            if (string.IsNullOrEmpty(payloadString))
            {
                return(Task.CompletedTask);
            }

            var payLoad = JsonConvert.DeserializeObject <Dictionary <string, string> >(payloadString);
            var token   = payLoad["token"];

            if (string.IsNullOrEmpty(token))
            {
                return(Task.CompletedTask);
            }

            var loginSession = QTDBRepository.UserLoginTokenRepository.GetAll()
                               .Include(x => x.User)
                               .FirstOrDefault(x => x.Token == token);

            if (loginSession == null)
            {
                return(Task.CompletedTask);
            }

            //Check if user was banned
            if (loginSession?.User?.UserStatusId == UserStatusEnums.Deactive)
            {
                return(Task.CompletedTask);
            }

            if (loginSession.ExpiredDated < DateTimeHelper.GetDateTimeNow())
            {
                return(Task.CompletedTask);
            }


            loginSession.LastLoginDated = DateTimeHelper.GetDateTimeNow();
            loginSession.ExpiredDated   = DateTimeHelper.GetDateTimeNow().AddDays(loginSession.IsRememberMe.GetValueOrDefault() ? 14 : 1);

            QTDBRepository.UserLoginTokenRepository.Save(loginSession);
            QTDBRepository.Commit();
            var requireClaim = GetRequireClaimFromControllerAndActionName(mvcContext.RouteData.Values["controller"] + "", mvcContext.RouteData.Values["action"] + "");

            if (!CheckClaimExistsInDatabase(requireClaim))
            {
                this.CreateNewClaim(requireClaim);
            }
            if (!CheckClaims(requireClaim, loginSession.UserId))
            {
#if DEBUG
                var userRole = QTDBRepository.UserRoleRepository.GetAll().Where(x => x.UserId.HasValue && x.UserId.Value == loginSession.UserId).Select(x => x.Role).OrderByDescending(x => x.RoleType).FirstOrDefault();
                var link     = "/api/role/grant-access?c=" + requireClaim + "&r=" + (int)userRole.RoleType;
                Debugger.Break();
#endif
                return(Task.CompletedTask);
            }
            foreach (var requirement in context.Requirements)
            {
                context.Succeed(requirement);
            }

            return(Task.CompletedTask);
        }