Beispiel #1
0
        public static rs Decode(string token = "")
        {
            rs  r;
            var secret = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";

            try
            {
                IJsonSerializer   serializer = new JsonNetSerializer();
                IDateTimeProvider provider   = new UtcDateTimeProvider();
                IJwtValidator     validator  = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtDecoder       decoder    = new JwtDecoder(serializer, validator, urlEncoder);

                //
                var           json  = decoder.Decode(token, secret, verify: true);
                JwtLoginModel model = JsonConvert.DeserializeObject <JwtLoginModel>(json);
                r = rs.T("Ok", model);
            }
            catch (TokenExpiredException)
            {
                r = rs.F("Token has expired");
            }
            catch (SignatureVerificationException)
            {
                r = rs.F("Token has invalid signature");
            }
            return(r);
        }
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            loginVM logvm = MySsAuthUsers.GetAuth();

            if (logvm == null)
            {
                var jsonnn = myCookies.Get("auth");
                if (!string.IsNullOrWhiteSpace(jsonnn))
                {
                    try
                    {
                        rs rsdecode = EncodeDecodeJWT.Decode(jsonnn);
                        if (rsdecode.r && rsdecode.v != null)
                        {
                            JwtLoginModel user_cook = (JwtLoginModel)rsdecode.v;
                            var           log       = _userServ.GetEntry(user_cook.uid);
                            var           quanids   = log.UserQuans.Select(s => s.QuanID).ToList();
                            if (log.QuanDefaultId == null)
                            {
                                requestContext.HttpContext.Response.Clear();
                                requestContext.HttpContext.Response.Redirect(Url.Action("ChonQuan", "Quan", new{ area = "Admin" }));
                                requestContext.HttpContext.Response.End();
                            }
                            logvm = new loginVM(log);
                            MySsAuthUsers.setLogin(logvm);
                        }
                    }
                    catch (Exception ex)
                    {
                        //_userServ.SSLogOut();
                    }
                }
            }

            __langid  = myCookies.GetLangKey();
            __setting = _settingServ.GetSetting();
            __config  = _confServ.GetConfigCache();
            HitCounter();
            ViewBag.__config  = __config;
            ViewBag.__setting = __setting;
            VIEWSETTING __viewsetting = new VIEWSETTING();

            __viewsetting.__config  = __config;
            __viewsetting.__setting = __setting;
            __viewsetting.__login   = MySsAuthUsers.GetAuth();
            ViewBag.__viewsetting   = __viewsetting; //VIEWSETTING __vs = ViewBag.__viewsetting;
            base.Initialize(requestContext);
        }
Beispiel #3
0
        public async Task <(string, DateTime)> Login(JwtLoginModel model)
        {
            var user = await _userManager.FindByNameAsync(model.UserName);

            if (user == null)
            {
                throw new UserNotFoundException();
            }

            if (user.LockoutEnabled && user.LockoutEnd > DateTime.Now)
            {
                throw new UserLockedOutException();
            }

            if (!await _userManager.CheckPasswordAsync(user, model.Password))
            {
                throw new PasswordIncorrectException();
            }

            var userRoles = await _userManager.GetRolesAsync(user);

            var authClaims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, user.Id),
                new Claim(JwtRegisteredClaimNames.Sub, user.Email),
            };

            foreach (var userRole in userRoles)
            {
                authClaims.Add(new Claim(ClaimTypes.Role, userRole));
            }

            var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.Jwt.Secret));

            var expirationDate = DateTime.Now.AddMonths(1);

            var jwtSecurityToken = new JwtSecurityToken(
                issuer: _config.Jwt.ValidIssuer,
                audience: _config.Jwt.ValidAudience,
                expires: expirationDate,
                claims: authClaims,
                signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256));

            string token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

            return(token, expirationDate);
        }
Beispiel #4
0
        // This method must be thread-safe since it is called by the thread-safe OnCacheAuthorization() method.

        /*
         * Phương thức này phải được thread-safe  vì nó được gọi bởi các phương thức Authorization cache thread-safe ()
         * cái đích của phương thức này là kiểm tra xem user đó đăng nhập đúng hay ko, có quền hay ko có quề
         * true: có quền
         * false: không có quên - > simple that!
         *
         */


        protected virtual bool AuthorizeCore(HttpContextBase httpContext)
        {
            this._userServ = DependencyResolver.Current.GetService <IUserRepository>();
            try
            {
                if (httpContext == null)
                {
                    throw new ArgumentNullException("httpContext");
                }

                loginVM logvm = MySsAuthUsers.GetAuth();
                if (logvm == null)
                {
                    var jsonnn = myCookies.Get("auth");
                    if (!string.IsNullOrWhiteSpace(jsonnn))
                    {
                        try
                        {
                            rs rsdecode = EncodeDecodeJWT.Decode(jsonnn);
                            if (rsdecode.r && rsdecode.v != null)
                            {
                                JwtLoginModel user_cook = (JwtLoginModel)rsdecode.v;
                                var           log       = _userServ.GetEntry(user_cook.uid);
                                logvm = new loginVM(log);
                                MySsAuthUsers.setLogin(logvm);
                            }
                        }
                        catch (Exception ex)
                        {
                            // _userServ.SSLogOut();
                            return(false);
                        }
                    }
                }
                if (logvm == null)
                {
                    return(false);
                }
                var user_login = _userServ.SSgetUserLoged();
                //Auth2. kiểm tra quền hạn theo username

                if (_usersSplit.Length > 0 &&
                    !_usersSplit.Contains(user_login.Username, StringComparer.OrdinalIgnoreCase))
                {
                    return(false);
                }

                if (_rolesSplit.Length > 0 && !_rolesSplit.Contains(user_login.RoleId.ToString()))
                {
                    return(false);
                }

                //Auth3. Kiểm tra quền hạn theo access role
                if (user_login.Username != "admin")
                {
                    if (_quyensSplit.Length > 0 && !IsInRole(user_login.ne_quyenIntArrStr, _quyensSplit))
                    {
                        return(false);
                    }
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }