Exemplo n.º 1
0
        private MyResult <object> CheckToken(string token, string sign)
        {
            MyResult <object> result = new MyResult <object>();

            try
            {
                //sign==
                if (!SecurityUtil.ValidSign(sign, token, Constants.Key))
                {
                    return(result.SetStatus(ErrorCode.ReLogin, "sign error 请联系管理员"));
                }
                //token==
                string json = DataProtectionUtil.UnProtect(token);
                if (string.IsNullOrEmpty(json))
                {
                    return(result.SetStatus(ErrorCode.ReLogin, "token error 请重新登录"));
                }
                TokenModel = json.GetModel <TokenModel>();
                if (TokenModel == null)
                {
                    return(result.SetStatus(ErrorCode.InvalidToken, "非法token"));
                }
                if (TokenModel.Id < 1)
                {
                    return(result.SetStatus(ErrorCode.InvalidToken, "无效token"));
                }
            }
            catch (System.Exception ex)
            {
                return(result.SetStatus(ErrorCode.SystemError, $"请求失败{ex.Message}"));
            }
            return(result);
        }
Exemplo n.º 2
0
        public MyResult <object> GetUserAuth(string name, string password)
        {
            MyResult result = new MyResult();

            if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(password))
            {
                return(result.SetError("用户名密码不能为空"));
            }
            string auth_sql = $"select au.id,au.username,au.password,au.role_id roleId,ifnull(ar.role_name,'') roleName from admin_users au left join admin_roles ar on au.role_id=ar.id where au.username='******' and au.password='******'";
            var    userInfo = dbConnection.QuerySingleOrDefault(auth_sql);

            if (userInfo == null)
            {
                return(result.SetStatus(ErrorCode.ErrorUserNameOrPass, "用户名密码错误"));
            }
            var        roleId     = userInfo.roleId;
            string     action_sql = $"select aa.action_name actionName,aa.code from admin_role_action ara left join admin_actions aa on ara.action_id=aa.id and aa.enable=1 where ara.role_id={roleId}";
            var        action     = dbConnection.Query(action_sql);
            TokenModel tokenModel = new TokenModel();

            tokenModel.Id     = userInfo.id;
            tokenModel.Mobile = "";
            tokenModel.Code   = "";
            tokenModel.Source = domain.enums.SourceType.Web;
            result.Data       = new
            {
                token    = DataProtectionUtil.Protect(tokenModel.GetJson()),
                userData = new
                {
                    userInfo = userInfo,
                    action   = action
                }
            };
            return(result);
        }
Exemplo n.º 3
0
        public BackstageCookie GetUserCook()
        {
            string          cookie = DataProtectionUtil.UnProtect(CookieUtil.GetCookie(Constants.WEBSITE_AUTHENTICATION_SCHEME));
            BackstageCookie back   = new BackstageCookie();

            back = cookie.GetModel <BackstageCookie>();
            return(back);
        }
Exemplo n.º 4
0
        public IActionResult ValidateCode()
        {
            ValidateCode _vierificationCodeServices = new ValidateCode();
            string       code = "";

            System.IO.MemoryStream ms = _vierificationCodeServices.Create(out code);
            CookieUtil.AppendCookie(Constants.WEBSITE_VERIFICATION_CODE, DataProtectionUtil.Protect(code));
            return(File(ms.ToArray(), @"image/png"));
        }
Exemplo n.º 5
0
        public MyResult <object> Login(BackstageUserAdd model)
        {
            MyResult result      = new MyResult();
            string   sessionCode = string.Empty;

            try
            {
                var code = CookieUtil.GetCookie(Constants.WEBSITE_VERIFICATION_CODE);
                if (code != null)
                {
                    sessionCode = DataProtectionUtil.UnProtect(code);
                }
            }
            catch (Exception ex)
            {
                LogUtil <AccountService> .Error(ex.Message);
            }
            if (model.ErrCount >= 3)
            {
                if (!model.VerCode.ToString().ToLower().Equals(sessionCode.ToLower()))
                {
                    return(result.SetStatus(ErrorCode.NotFound, "验证码输入不正确!"));
                }
            }

            BackstageUser account = this.First <BackstageUser>(t => t.LoginName == model.LoginName);

            if (account == null)
            {
                return(result.SetStatus(ErrorCode.NotFound, "账号不存在!"));
            }
            string pwd = SecurityUtil.MD5(model.Password);

            if (!account.Password.Equals(pwd, StringComparison.OrdinalIgnoreCase))
            {
                return(result.SetStatus(ErrorCode.InvalidPassword));
            }
            switch (account.AccountStatus)
            {
            case (int)AccountStatus.Disabled:
                return(result.SetStatus(ErrorCode.AccountDisabled, "账号不可用!"));
            }

            account.LastLoginTime = DateTime.Now;
            account.LastLoginIp   = "";//MvcHelper.ClientIP;
            this.Update(account, true);
            MvcIdentity identity = new MvcIdentity(account.Id, account.LoginName, account.LoginName, account.Email, (int)account.RoleId, null, account.LastLoginTime);

            identity.Login(Constants.WEBSITE_AUTHENTICATION_SCHEME, x =>
            {
                x.Expires  = DateTime.Now.AddHours(5);//滑动过期时间
                x.HttpOnly = true;
            });

            return(result);
        }
Exemplo n.º 6
0
        public static string GetEncryptedString(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return(str);
            }

            if (IsEncrypted(str))
            {
                return(str);
            }

            if (UseDapi)
            {
                str = DataProtectionUtil.Encrypt(str);
            }
            else
            {
                str = CryptoUtil.Encrypt(str, password, CryptoUtil.CryptoProviderDES);
            }
            return(encryptionPrefix + str + encryptionSuffix);
        }
Exemplo n.º 7
0
        public MyResult <object> Login(WxLoginDto model)
        {
            MyResult result = new MyResult();

            if (string.IsNullOrEmpty(model.Code))
            {
                return(result.SetStatus(ErrorCode.InvalidData, "code 无效"));
            }
            var code2SessionUrl = $"https://api.weixin.qq.com/sns/jscode2session?appid={Constants.WxAppId}&secret={Constants.WxSecret}&js_code={model.Code}&grant_type=authorization_code";
            var rep             = HttpUtil.GetString(code2SessionUrl);
            var repObj          = rep.GetModel <Code2SessionRep>();
            var openid          = repObj.OpenId;
            var user            = base.First <User>(predicate => predicate.OpenId == openid);

            if (user == null)
            {
                return(result.SetStatus(ErrorCode.NotFound, "用户未注册"));
            }
            user.SessionKey = repObj.Session_Key;
            TokenModel tokenModel = new TokenModel();

            tokenModel.Id     = (int)user.Id;
            tokenModel.Mobile = user.PhoneNum;
            tokenModel.Code   = repObj.OpenId;
            tokenModel.Source = domain.enums.SourceType.WeChat;
            var tokenStr = tokenModel.GetJson();
            var enToken  = DataProtectionUtil.Protect(tokenStr);

            result.Data = new
            {
                token = enToken,
                uid   = (int)user.Id
            };
            user.Token = enToken;
            base.Update(user, true);
            return(result);
        }
Exemplo n.º 8
0
        public static string GetDecrptedString(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return(str);
            }

            if (IsEncrypted(str))
            {
                str = str.Substring(encryptionPrefix.Length, str.Length - encryptionPrefix.Length - encryptionSuffix.Length);

                if (UseDapi)
                {
                    str = DataProtectionUtil.Decrypt(str);
                }
                else
                {
                    str = CryptoUtil.Decrypt(str, password, CryptoUtil.CryptoProviderDES);
                }
                return(str);
            }

            return(str);
        }
Exemplo n.º 9
0
 public void Login(string scheme, Action <CookieOptions> options = null)
 {
     CookieUtil.AppendCookie(scheme, DataProtectionUtil.Protect(JsonConvert.SerializeObject(this)), true, options);
 }
Exemplo n.º 10
0
        public virtual async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            AuthorizationPolicy effectivePolicy = Policy;

            if (effectivePolicy == null)
            {
                if (PolicyProvider == null)
                {
                    throw new InvalidOperationException("An AuthorizationPolicy cannot be created without a valid instance of IAuthorizationPolicyProvider.");
                }
                effectivePolicy = await AuthorizationPolicy.CombineAsync(PolicyProvider, AuthorizeData);
            }
            if (effectivePolicy != null)
            {
                MvcPrincipal newPrincipal  = null;
                string       currentScheme = effectivePolicy.AuthenticationSchemes.FirstOrDefault();
                if (!string.IsNullOrEmpty(currentScheme))
                {
                    if (!(context.HttpContext.User.Identity is MvcIdentity) || !context.HttpContext.User.Identity.IsAuthenticated)
                    {
                        string cookie = CookieUtil.GetCookie(currentScheme, true);
                        if (!string.IsNullOrEmpty(cookie))
                        {
                            try
                            {
                                string      value    = DataProtectionUtil.UnProtect(cookie);
                                MvcIdentity identity = JsonExtension.GetModel <MvcIdentity>(value, "");
                                if (identity != null)
                                {
                                    newPrincipal = identity.GetPrincipal();
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                    else
                    {
                        newPrincipal = (context.HttpContext.User as MvcPrincipal);
                    }
                }
                if (newPrincipal == null)
                {
                    context.HttpContext.User = MvcIdentity.Instance.GetPrincipal();
                }
                else
                {
                    context.HttpContext.User = newPrincipal;
                }
                if (!context.Filters.Any((IFilterMetadata item) => item is IAllowAnonymousFilter))
                {
                    if (context.HttpContext.User.Identity.IsAuthenticated)
                    {
                        if (AuthorizeFilter == null)
                        {
                            AuthorizeFilter = ServiceProviderServiceExtensions.GetService <IAuthorizeFilter>(context.HttpContext.RequestServices);
                        }
                        if (AuthorizeFilter != null)
                        {
                            await AuthorizeFilter.OnAuthorizedAsync(context, currentScheme);
                        }
                    }
                    else
                    {
                        context.Result = new ChallengeResult(effectivePolicy.AuthenticationSchemes.ToArray());
                    }
                }
            }
        }
Exemplo n.º 11
0
        public override Task OnActionExecutionAsync(Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext context, Microsoft.AspNetCore.Mvc.Filters.ActionExecutionDelegate next)
        {
            try
            {
                var userAgent = context.HttpContext.Request.Headers["User-Agent"].ToString();
                if (userAgent.Contains("MicroMessenger"))
                {
                    SourceType = SourceType.WeChatApp;
                }
                else if (userAgent.Contains("iPhone") || userAgent.Contains("iPod") || userAgent.Contains("iPad"))
                {
                    SourceType = SourceType.IOS;
                }
                else if (userAgent.Contains("Android"))
                {
                    SourceType = SourceType.Android;
                }
                else
                {
                    //TODO:the last del
                    SourceType = SourceType.Web;
                }
                foreach (var kv in context.HttpContext.Request.Query)
                {
                    ReqParams[kv.Key] = kv.Value.ToString();
                }
                if (context.HttpContext.Request.HasFormContentType)
                {
                    foreach (var kv in context.HttpContext.Request.Form)
                    {
                        ReqParams[kv.Key] = kv.Value.ToString();
                    }
                }
                var values = context.HttpContext.GetContextDict();
                foreach (var kv in values)
                {
                    ReqParams[kv.Key] = kv.Value.ToString();
                }
                if (SourceType == SourceType.Unknown)
                {
                    context.Result = new ObjectResult(new MyResult <object>().SetStatus(ErrorCode.Unauthorized, "请设置User-Agent请求头: 如:iPhone 或者 Android 或则web"));
                }
                else
                {
                    var token = string.Empty;
                    var sign  = string.Empty;
                    if (ReqParams.ContainsKey(TOKEN_NAME))
                    {
                        token = ReqParams[TOKEN_NAME];
                    }
                    if (ReqParams.ContainsKey(Sign))
                    {
                        sign = ReqParams[Sign];
                    }
                    //can get token from server redis now only get form params
                    // ..
                    //
                    if (!context.ActionDescriptor.FilterDescriptors.Any(t => t.Filter is AllowAnonymousFilter))//need check token
                    {
                        if (string.IsNullOrEmpty(token))
                        {
                            context.Result = new ObjectResult(new MyResult <object>(ErrorCode.Unauthorized, "token is empty you are error!"));
                        }
                        else if (string.IsNullOrEmpty(sign))
                        {
                            context.Result = new ObjectResult(new MyResult <object>(ErrorCode.Unauthorized, "sign is empty you are error!"));
                        }
                        else
                        {
                            var model = CheckToken(token, sign);
                            if (model.Success)
                            {
                                //ok
                            }
                            if (!model.Success)
                            {
                                context.Result = new ObjectResult(model);
                            }
                        }
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(token))
                        {
                            TokenModel = new TokenModel();
                        }
                        else
                        {
                            var json = DataProtectionUtil.UnProtect(token);
                            if (string.IsNullOrEmpty(json))
                            {
                                TokenModel = new TokenModel();
                            }
                            else
                            {
                                TokenModel = json.GetModel <TokenModel>();
                            }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                LogUtil <ApiBaseController> .Error(ex, ex.Message);

                context.Result = new ObjectResult(new MyResult <object>(ErrorCode.SystemError, $"请求失败{ex.Message}"));
            }
            return(base.OnActionExecutionAsync(context, next));
        }