示例#1
0
 public ActionResult OAuth2(string corpid, string accesstoken, string reurl, string scope = "snsapi_base")
 {
     #region 校验
     if (string.IsNullOrEmpty(reurl))
     {
         LogWriter.Info(string.Format("qyid为“{0}”的OAuth2授权失败,原因:reurl为空", corpid));
         return(Content("非法访问"));
     }
     var account = GetAccount(corpid);
     if (account == null)
     {
         LogWriter.Info(string.Format("qyid为“{0}”的OAuth2授权失败,原因:企业号不存在", corpid));
         return(Content("非法访问"));
     }
     var passtoken = GetPassToken(account, accesstoken);
     if (passtoken == null)
     {
         LogWriter.Info(string.Format("qyid为“{0}”的OAuth2授权失败,原因:accesstoken错误", corpid));
         return(Content("非法访问"));
     }
     if (!ValidateOauth2Domain(passtoken, Base64Helper.DecodeBase64(reurl.Replace(" ", "+"))))
     {
         LogWriter.Info(string.Format("qyid为“{0}”的OAuth2授权失败,原因:reurl{1}错误", corpid, reurl));
         return(Content("非法访问"));
     }
     #endregion
     string CorpID = account.CorpID;
     var    domain = Request.Url.Authority;
     var    url    = OAuth2Api.GetCode(CorpID, "http://" + domain + "/wechatservice/wxapi/OAuth2Callback?corpid=" + corpid + "&accesstoken=" + accesstoken + "&scope=" + scope + "&reurl=" + reurl, "JeffreySu", account.AgentId == null ? "" : account.AgentId.ToString(), scope: scope);
     return(Redirect(url));
 }
示例#2
0
        public ActionResult Identify(string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                return(Redirect(OAuth2Api.GetCode(_corpId, AbsoluteUri(), "STATE", _agentId)));
            }

            WxIdentifyDto dto = HttpContext.Session.GetObjectFromJson <WxIdentifyDto>("WxIdentify");

            if (dto == null)
            {
                LoginViewModel vm = new LoginViewModel()
                {
                    ReturnUrl = AbsoluteUri()
                };
                try {
                    var accessToken            = AccessTokenContainer.GetToken(_corpId, _secret);
                    GetUserInfoResult userInfo = OAuth2Api.GetUserId(accessToken, code);
                    vm.WorkerCn = userInfo.UserId;
                    vm.DeviceId = userInfo.DeviceId;
                }
                catch {
                    Logger.Error("微信授权错误");
                }
                return(View("login", vm));
            }
            else
            {
                return(View("TaskList", dto));
            }
        }
示例#3
0
        public ActionResult Login(string returnUrl, string code)
        {
            if (returnUrl == null)
            {
                return(null);
            }
            // 根据 returnUrl 得到 AppName, 然后得到_secret和_agentId
            string appName = _appDict[GetActionOfUrl(returnUrl)];

            _secret  = _appConfiguration[string.Format("SenparcWeixinSetting:{0}:Secret", appName)];
            _agentId = _appConfiguration[string.Format("SenparcWeixinSetting:{0}:AgentId", appName)];

            if (string.IsNullOrEmpty(code))
            {
                // 备案
                return(Redirect(OAuth2Api.GetCode(_corpId, AbsoluteUri(), "STATE", _agentId)));
            }

            var vm = new LoginViewModel()
            {
                ReturnUrl = returnUrl
            };

            try {
                var accessToken            = AccessTokenContainer.GetToken(_corpId, _secret);
                GetUserInfoResult userInfo = OAuth2Api.GetUserId(accessToken, code);
                vm.WorkerCn = userInfo.UserId;
                vm.DeviceId = userInfo.DeviceId;
            }
            catch {
                Logger.Error("微信登录错误");
            }

            return(View(vm));
        }
        public void ProcessRequest(HttpContext context)
        {
            if (!context.Request.IsAuthenticated)
            {
                LogManager.GetLogger(this.GetType()).Debug("UrlStart");
                string strUrl = OAuth2Api.GetCode(CorpId, HttpUtility.UrlEncode(webUrl + strRet), HttpUtility.UrlEncode(context.Request.RawUrl));
                LogManager.GetLogger(this.GetType()).Debug(strUrl);

                context.Response.Redirect(strUrl);
                return;
            }
            // 获取要请求的文件名
            string filePath = context.Server.MapPath(context.Request.FilePath);

            // 用Fiddler查看响应头,如果看到有这个头,就表示是由这段代码处理的。
            context.Response.AddHeader("SeesionExist", (context.Session != null ? "yes" : "no"));
            // 在这里,你可以访问context.Session
            // 设置响应内容标头
            FileInfo fi      = new FileInfo(filePath);
            var      strName = fi.Name;

            context.Response.ContentType = MimeMapping.GetMimeMapping(strName);

            // 输出文件内容
            context.Response.TransmitFile(filePath);
        }
示例#5
0
        public IActionResult Index(string returnUrl)
        {
            var redirectUrl = "http://" + HttpContext.Request.Host.Host + "/OAuth2/UserInfoCallback?returnUrl=" + returnUrl.UrlEncode();
            var url         = OAuth2Api.GetCode(_corpId, redirectUrl, "", _agentId);

            return(Redirect(url));
        }
        public IActionResult Index(string returnUrl)
        {
            //string state = "Zodolabs-Asset-" + DateTime.Now.Millisecond;
            var redirectUrl = "http://" + HttpContext.Request.Host.Host + "/OAuth2/UserInfoCallback?returnUrl=" + returnUrl.UrlEncode();
            var url         = OAuth2Api.GetCode(_corpId, redirectUrl, "", _agentId);

            return(Redirect(url));
        }
示例#7
0
        public ActionResult Oil(string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                return(Redirect(OAuth2Api.GetCode(_corpId, AbsoluteUri(), "STATE", _agentId)));
            }

            string workerCn = null;

            try {
                var accessToken            = AccessTokenContainer.GetToken(_corpId, _secret);
                GetUserInfoResult userInfo = OAuth2Api.GetUserId(accessToken, code);
                workerCn = userInfo.UserId;
            }
            catch {
                Logger.Error("微信授权错误");
            }

            if (workerCn == null)
            {
                return(Content("系统取不到你的微信标识号"));
            }
            //workerCn = "90005";
            var worker = WorkManager.GetWorkerByCn(workerCn);

            if (!worker.WorkRoleNames.Contains("司机"))
            {
                return(Content("需要司机角色"));
            }
            var depot = WorkManager.GetDepot(worker.DepotId);
            var vm    = new OilViewModel();

            vm.WorkerId = worker.Id;

            foreach (var v in _vehicleCache.GetList().FindAll(x => x.DepotId == depot.Id))
            {
                vm.Vehicles.Add(new ComboItemModel()
                {
                    Id = v.Id, Name = v.Cn + v.License
                });
            }
            foreach (var v in _gasStationCache.GetList().FindAll(x => string.IsNullOrEmpty(x.DepotList) || x.DepotList.Contains(depot.Name)))
            {
                vm.GasStations.Add(new ComboItemModel()
                {
                    Id = v.Id, Name = v.Name
                });
            }
            foreach (var t in _oilTypeCache.GetList())
            {
                vm.OilTypes.Add(new ComboItemModel()
                {
                    Id = t.Id, Name = t.Name
                });
            }

            return(View(vm));
        }
        public ActionResult Authorize(string state, string scope)
        {
            if (SSOClient.IsLogin)
            {
                return(ToMenu(state));
            }

            return(Redirect(OAuth2Api.GetCode(_corpId, _authorizeUrl, state, _agentid, _response_type, scope)));
        }
示例#9
0
        // GET: QYOAuth2
        public ActionResult Index()
        {
            var state = "Wangkai-" + DateTime.Now.Millisecond; //随机数,用于识别请求可靠性

            Session["State"] = state;                          //储存随机数到Session
            string code = OAuth2Api.GetCode(CorpId, "http://1p623v6690.iok.la/QYOAuth2/ShowContent", state, "code", "snsapi_base");

            ViewData["UrlBase"] = code;
            return(View()); //https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx140262311b599a34&redirect_uri=http://mpwechatserver.chinacloudsites.cn/oauth2/QYBaseCallback&response_type=code&scope=snsapi_base&state=TJMicroPower#wechat_redirect
        }
示例#10
0
        /// <summary>
        /// 微信网页授权
        /// </summary>
        /// <param name="appcode">应用编码 默认为移动审批</param>
        /// <param name="returnUrl">返回url</param>
        /// <returns></returns>
        public ActionResult Authorize(string appcode = null, string returnUrl = null)
        {
            //默认移动审批应用
            appcode   = appcode ?? Constants.MOBILE_APPROVAL_TEST;
            returnUrl = returnUrl ?? Request.UrlReferrer?.ToString();
            var redirectUrl = $"http://douhua.oicp.net/wechat/consumecode?appcode={appcode}&returnUrl={returnUrl}";
            var target      = OAuth2Api.GetCode(corpId, redirectUrl, "", "");

            return(Redirect(target));
        }
        public IActionResult 异常填报_Post(Wx异常说明 model)
        {
            if (model == null)
            {
                return(RedirectToAction(nameof(填报失败), "异常说明"));
            }

            var memberResult = AppSessions.GetMember();

            if (memberResult == null)
            {
                return(Redirect(OAuth2Api.GetCode(WeixinOptions.CorpId, "wx.pinhuadashi.com%2Fwxclock%2Foauth%3Freturnurl%3D%252Fwxclock%252Findex", "STATE")));
            }

            model.用户号 = memberResult.userid;
            model.姓名  = memberResult.name;

            if (!model.时间.HasValue || !model.类型.HasValue || string.IsNullOrEmpty(model.用户号))
            {
                return(RedirectToAction(nameof(填报失败), "异常说明"));
            }

            var rtId = "148.1";
            var rcId = pinhuaContext.GetNewRcId();

            model.ExcelServerRtid = rtId;
            model.ExcelServerRcid = rcId;
            model.是否通知            = 0;
            model.是否处理            = 0;
            model.填报时间            = DateTime.Now;

            var repCase = new EsRepCase
            {
                RcId          = rcId,
                RtId          = rtId,
                LstFiller     = 2,
                LstFillerName = memberResult.name,
                LstFillDate   = DateTime.Now,
                FillDate      = DateTime.Now,
            };

            pinhuaContext.EsRepCase.Add(repCase);
            pinhuaContext.Wx异常说明.Add(model);
            var iRet = pinhuaContext.SaveChanges();

            if (iRet > 0)
            {
                return(RedirectToAction(nameof(填报成功), "异常说明"));
            }
            else
            {
                return(RedirectToAction(nameof(填报失败), "异常说明"));
            }
        }
 public ActionResult WeixinAddr(string type)
 {
     if (type == "GZH") //公众号
     {
         return(Redirect(OAuthApi.GetAuthorizeUrl("wx806943202a75a124", "http%3A%2F%2Fbit.bitdao.cn%2Fauth%2Fweixingzhsignin", "1", OAuthScope.snsapi_base)));
     }
     else
     {
         return(Redirect(OAuth2Api.GetCode("wx806943202a75a124", "http%3A%2F%2Fbit.bitdao.cn%2Fauth%2Fweixinqyhsignin", "1", "")));
     }
 }
        public IActionResult Index()
        {
            var memberResult = AppSessions.GetMember();

            if (memberResult == null)
            {
                return(Redirect(OAuth2Api.GetCode(WeixinOptions.CorpId, "wx.pinhuadashi.com%2Fwxclock%2Foauth%3Freturnurl%3D%252Fwxclock%252Findex", "STATE")));
            }

            return(View(memberResult));
        }
示例#14
0
        public IActionResult Tab4()
        {
            var memberResult = AppSessions.GetMember();

            if (memberResult == null)
            {
                return(Redirect(OAuth2Api.GetCode(WeixinOptions.CorpId, "wx.pinhuadashi.com%2Fwxclock%2Foauth%3Freturnurl%3D%252Fwxclock%252Findex", "STATE")));
            }

            ViewData[nameof(GetDepartmentListResult)] = GetDepartmentList();

            return(View(memberResult));
        }
示例#15
0
        public IActionResult Index(string returnUrl)
        {
            // 设置自己的 URL
            var url = "https://4424-222-93-135-159.ngrok.io";

            //此页面引导用户点击授权
            var oauthUrl =
                OAuth2Api.GetCode(_corpId, $"{url}/OAuth2/BaseCallback?returnUrl={returnUrl.UrlEncode()}",
                                  null, null);//snsapi_base方式回调地址

            ViewData["UrlBase"]   = oauthUrl;
            ViewData["returnUrl"] = returnUrl;

            return(View());
        }
示例#16
0
        public IActionResult 待办审批DisAgree(Wx异常说明 model)
        {
            if (model == null)
            {
                return(View());
            }

            var memberResult = AppSessions.GetMember();

            if (memberResult == null)
            {
                return(Redirect(OAuth2Api.GetCode(WeixinOptions.CorpId, "wx.pinhuadashi.com%2Fwxclock%2Foauth%3Freturnurl%3D%252Fwxclock%252Findex", "STATE")));
            }

            pinhuaContext.Wx异常说明.Where(p => p.ExcelServerRcid == model.ExcelServerRcid).FirstOrDefault().是否处理 = 2;
            pinhuaContext.Wx异常说明.Where(p => p.ExcelServerRcid == model.ExcelServerRcid).FirstOrDefault().处理人  = memberResult.name;
            pinhuaContext.Wx异常说明.Where(p => p.ExcelServerRcid == model.ExcelServerRcid).FirstOrDefault().处理时间 = DateTime.Now;
            pinhuaContext.SaveChanges();

            return(RedirectToAction("Index", "WxClock", new { member = JsonConvert.SerializeObject(memberResult) }));
        }
示例#17
0
        protected bool SetAuth(HttpContext hc)
        {
            if (!(hc.Request.IsAuthenticated && hc.User.Identity != null))
            {
                //      LogManager.GetLogger(this.GetType()).Error("1");
                hc.Session["ReturnUrl"] = hc.Request.Url.AbsoluteUri;
                //   LogManager.GetLogger(this.GetType()).Error("2");
                var objConfig = WeChatCommonService.GetWeChatConfig(2);
                //  LogManager.GetLogger(this.GetType()).Error("3");
                string CorpId = objConfig.WeixinCorpId;
                string strRet = WebConfigurationManager.AppSettings["UserBackUrl"];
                //  LogManager.GetLogger(this.GetType()).Error("4");
                // LogManager.GetLogger(this.GetType()).Debug("UrlStart");
                string strUrl = OAuth2Api.GetCode(CorpId, hc.Server.UrlEncode(strRet), "About");
                //  LogManager.GetLogger(this.GetType()).Error("5");
                hc.Response.Redirect(strUrl);

                return(false);
            }

            return(true);
            // LogManager.GetLogger(this.GetType()).Debug(strUrl);
        }
        /// <param name="corpId">企业的CorpID</param>
        /// <param name="redirectUrl">授权后重定向的回调链接地址,请使用urlencode对链接进行处理</param>
        /// <param name="agentId">企业应用的id。当scope是snsapi_userinfo或snsapi_privateinfo时,该参数必填。意redirect_uri的域名必须与该应用的可信域名一致。</param>
        /// <param name="state">重定向后会带上state参数,企业可以填写a-zA-Z0-9的参数值</param>
        /// <param name="responseType">返回类型,此时固定为:code</param>
        /// <param name="scope">应用授权作用域,此时固定为:snsapi_base</param>
        /// #wechat_redirect 微信终端使用此参数判断是否需要带上身份信息
        /// 员工点击后,页面将跳转至 redirect_uri/?code=CODE&state=STATE,企业可根据code参数获得员工的userid。
        ///
        // GET: UserInfo
        public ActionResult GetUserInfo()
        {
            //GetUserInfoResult userInfo = new GetUserInfoResult();
            String corpId       = "wxcf995f1b81a19a41";  //企业ID
            String redirectUrl  = "27.211.236.58:53902"; //重定向URL
            String state        = "cg";                  //状态参数
            String agentId      = "1000003";             //企业应用ID
            String responseType = "code";                //返回类型,此时固定为:code
            String scope        = "snsapi_userinfo";     //应用授权作用域,此时固定为:snsapi_base   snsapi_userinfo
            //通过授权获取到 Code
            String codeUrl = OAuth2Api.GetCode(corpId, redirectUrl, state, agentId, responseType, scope);

            ViewData["url"] = codeUrl;

            /*
             * Console.WriteLine(codeUrl);
             * String secret = "pxPQ6jDtAtBQf34dci2QPpcXc1nhgoBSQUQNhxXGfII";
             * AccessTokenResult accessTokenResult = AccessTokenContainer.GetTokenResult(corpId,secret,false);
             * String accessToken = accessTokenResult.access_token;
             * Console.WriteLine(accessToken);
             */
            return(View());
        }
示例#19
0
        public IActionResult GetOpenId(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                id = "/";
            }
#if DEBUG
            return(Redirect($"/#/wxhub/{WebUtility.UrlEncode("黄继业")}/{WebUtility.UrlEncode("13907741118")}/{false}/{0}/{WebUtility.UrlEncode(id)}"));
#else
            if (!string.IsNullOrWhiteSpace(UserName) &&
                !string.IsNullOrWhiteSpace(UserId) &&
                !string.IsNullOrWhiteSpace(IsAdmin) &&
                !string.IsNullOrWhiteSpace(IsLeader))
            {
                return(Redirect($"/#/wxhub/{WebUtility.UrlEncode(UserName)}/{WebUtility.UrlEncode(UserId)}/{IsAdmin}/{IsLeader}/{WebUtility.UrlEncode(id)}"));
            }

            var state = Request.Query["state"];
            if (state != "car0774")
            {
                return(Redirect(OAuth2Api.GetCode(option.CorpId, "https://" + Request.Host + Request.Path + Request.QueryString, "car0774", "")));
            }
            else
            {
                option.AccessToken = AccessTokenContainer.TryGetToken(this.option.CorpId, this.option.Secret);
                var code     = Request.Query["code"];
                var at       = OAuth2Api.GetUserId(option.AccessToken, code);
                var userinfo = MailListApi.GetMember(option.AccessToken, at.UserId);
                UserName = userinfo.name;
                UserId   = at.UserId;
                IsAdmin  = userinfo.department.Contains(7).ToString();
                IsLeader = userinfo.isleader.ToString();
                //超级管理员的部门id为7
                return(Redirect($"/#/wxhub/{WebUtility.UrlEncode(userinfo.name)}/{WebUtility.UrlEncode(at.UserId)}/{userinfo.department.Contains(7)}/{userinfo.isleader}/{WebUtility.UrlEncode(id)}"));
            }
#endif
        }
        private string GetWeChatUserID(ActionExecutingContext filterContext)
        {
            //var objLoginInfo = Session["UserInfo"] as WechatUser;

            //LogManager.GetLogger(this.GetType()).Debug("objLoginInfo : " + (objLoginInfo == null?"NULL":objLoginInfo.WeChatUserID));
            ////判断用户是否为空
            //if (objLoginInfo == null)

            //LogManager.GetLogger(this.GetType()).Debug("objLoginInfo is null");

            //判断是否已经登陆
            var User = GetLoginUserInfo();

            if (!string.IsNullOrEmpty(User) && (objLoginInfo.Id > 0 || Request["_Callback"] == "1" || Request.Url.AbsoluteUri.Contains("_Callback=1")) /*防止死循环*/)
            {
                return(User);
            }


            string strToUrl = Request.RawUrl.Replace(":5001", ""); //处理反向代理

            Session["ReturnUrl"] = strToUrl;                       // Request.Url.ToString();
            var    weChatConfig = WeChatCommonService.GetWeChatConfigByID(AppId);
            string strUrl;

            string strRet     = CommonService.GetSysConfig("UserBackUrl", "");
            string webUrl     = CommonService.GetSysConfig("WeChatUrl", "");
            string strBackUrl = string.Format("{0}{1}?wechatid={2}", webUrl, strRet.Trim('/'), AppId);

            log.Debug("UrlStart :" + strBackUrl);



            //服务号
            if (weChatConfig.IsCorp.HasValue && !weChatConfig.IsCorp.Value)
            {
                strUrl = Innocellence.Weixin.MP.AdvancedAPIs.OAuthApi.GetAuthorizeUrl(weChatConfig.WeixinCorpId, strBackUrl, Guid.NewGuid().ToString(), Weixin.MP.OAuthScope.snsapi_base);
            }
            else //企业号
            {
                //string strRet = WebConfigurationManager.AppSettings["UserBackUrl"];
                //string webUrl = CommonService.GetSysConfig("WeChatUrl", "");

                // string strBackUrl = string.Format("{0}{1}?wechatid={2}", webUrl, strRet, AppId);

                //log.Debug("UrlStart :" + strBackUrl);
                //strUrl = OAuth2Api.GetCode(weChatConfig.WeixinCorpId, strBackUrl, Server.UrlEncode(strToUrl));
                strUrl = OAuth2Api.GetCode(weChatConfig.WeixinCorpId, strBackUrl, Guid.NewGuid().ToString());
            }

            log.Debug(strUrl);

            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                AjaxResult <int> result = new AjaxResult <int>();
                result.Message       = new JsonMessage((int)HttpStatusCode.Unauthorized, strUrl);
                filterContext.Result = Json(result, JsonRequestBehavior.AllowGet);
            }
            else
            {
                log.Debug("filterContext.Result : " + strUrl);
                filterContext.Result = new RedirectResult(strUrl);
            }

            //if (null != filterContext.ActionDescriptor && "WxDetail".Equals(filterContext.ActionDescriptor.ActionName, StringComparison.OrdinalIgnoreCase))
            //{
            //    backRedirectUrl = strUrl;
            //    log.Debug("backRedirectUrl : " + backRedirectUrl);
            //}
            return(string.Empty);
        }
示例#21
0
        private string GetLillyId(ActionExecutingContext filterContext)
        {
            //var objLoginInfo = Session["UserInfo"] as WechatUser;

            //LogManager.GetLogger(this.GetType()).Debug("objLoginInfo : " + (objLoginInfo == null?"NULL":objLoginInfo.LillyID));
            ////判断用户是否为空
            //if (objLoginInfo == null)
            {
                //LogManager.GetLogger(this.GetType()).Debug("objLoginInfo is null");
                if (HttpContext.Request.IsAuthenticated)
                {
                    LogManager.GetLogger(this.GetType()).Debug("HttpContext.Request.IsAuthenticated");
                    if (Request.UserAgent.IndexOf("MicroMessenger") >= 0)
                    {
                        LogManager.GetLogger(this.GetType()).Debug("WeChat Browser");
                        var windowsIdentity = User.Identity;
                        if (windowsIdentity != null)
                        {
                            return(windowsIdentity.Name);
                        }
                        else
                        {
                            return(string.Empty);
                        }
                        //LogManager.GetLogger(this.GetType()).Debug("User.Identity" + User.Identity.Name);
                        //SysUserService objServ = new SysUserService();
                        //var objUser = objServ.AutoLogin(windowsIdentity);
                        //if (objUser != null)
                        //{
                        //    objLoginInfo = new WechatUser() { LillyID = objUser.UserName, WechatID = objUser.UserName };
                        //    Session["UserInfo"] = objLoginInfo;
                        //    return objUser.UserName;
                        //}
                        //else
                        //{
                        //    LogManager.GetLogger(this.GetType()).Debug("objUser is still NULL");
                        //}
                    }
                }
                else
                {
                    LogManager.GetLogger(this.GetType()).Debug("SessionId:" + Session.SessionID);
                    Session["ReturnUrl"] = Request.RawUrl;// Request.Url.ToString();


                    string strRet = WebConfigurationManager.AppSettings["UserBackUrl"];
                    string webUrl = WebConfigurationManager.AppSettings["WebUrl"];

                    LogManager.GetLogger(this.GetType()).Debug("UrlStart");
                    string strUrl = OAuth2Api.GetCode(CorpId, Server.UrlEncode(webUrl + strRet), Server.UrlEncode(Request.RawUrl));
                    LogManager.GetLogger(this.GetType()).Debug(strUrl);

                    if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                    {
                        AjaxResult <int> result = new AjaxResult <int>();
                        result.Message       = new JsonMessage((int)HttpStatusCode.Unauthorized, strUrl);
                        filterContext.Result = Json(result, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        LogManager.GetLogger(this.GetType()).Debug("filterContext.Result = new RedirectResult(strUrl) : " + strUrl);
                        filterContext.Result = new RedirectResult(strUrl);
                    }
                    return(string.Empty);
                }
            }
            return(string.Empty);
        }
示例#22
0
 public static string GetCode(string returnUrl)
 {
     return(OAuth2Api.GetCode(CORPID, returnUrl, "STATE"));
 }
        public string GetCode(string redirectUrl, string state)
        {
            var corpId = WeixinConfig.GetCorpId();

            return(OAuth2Api.GetCode(corpId, redirectUrl, state));
        }
        private string GetWeChatUserID(ActionExecutingContext filterContext)
        {
            string strwechatid = Request["wechatid"];

            if (string.IsNullOrEmpty(strwechatid) && RouteData.Values.ContainsKey("appid"))
            {
                strwechatid = RouteData.Values["appid"].ToString();
            }
            else if (string.IsNullOrEmpty(strwechatid))
            {
                log.Error("wechatid not found!" + Request.Url);
                filterContext.Result = new ContentResult()
                {
                    Content = "wechatid not found!"
                };
                return(null);
            }

            AppId = int.Parse(strwechatid);
            //var objLoginInfo = Session["UserInfo"] as WechatUser;

            //LogManager.GetLogger(this.GetType()).Debug("objLoginInfo : " + (objLoginInfo == null?"NULL":objLoginInfo.WeChatUserID));
            ////判断用户是否为空
            //if (objLoginInfo == null)
            {
                //LogManager.GetLogger(this.GetType()).Debug("objLoginInfo is null");
                if (HttpContext.Request.IsAuthenticated)
                {
                    log.Debug("HttpContext.Request.IsAuthenticated");
                    if (Request.UserAgent.IndexOf("MicroMessenger") >= 0)
                    {
                        log.Debug("WeChat Browser");
                        var windowsIdentity = User.Identity;
                        if (windowsIdentity != null)
                        {
                            return(windowsIdentity.Name);
                        }
                        else
                        {
                            return(string.Empty);
                        }
                        //LogManager.GetLogger(this.GetType()).Debug("User.Identity" + User.Identity.Name);
                        //SysUserService objServ = new SysUserService();
                        //var objUser = objServ.AutoLogin(windowsIdentity);
                        //if (objUser != null)
                        //{
                        //    objLoginInfo = new WechatUser() { WeChatUserID = objUser.UserName, WechatID = objUser.UserName };
                        //    Session["UserInfo"] = objLoginInfo;
                        //    return objUser.UserName;
                        //}
                        //else
                        //{
                        //    LogManager.GetLogger(this.GetType()).Debug("objUser is still NULL");
                        //}
                    }
                }
                else
                {
                    log.Debug("SessionId:" + Session.SessionID);
                    Session["ReturnUrl"] = Request.RawUrl;// Request.Url.ToString();


                    string strRet = WebConfigurationManager.AppSettings["UserBackUrl"];
                    string webUrl = CommonService.GetSysConfig("WeChatUrl", "");



                    string strBackUrl = string.Format("{0}{1}?wechatid={2}", webUrl, strRet, strwechatid);

                    log.Debug("UrlStart :" + strBackUrl);

                    var weChatConfig = WeChatCommonService.GetWeChatConfigByID(int.Parse(strwechatid));

                    string strUrl = OAuth2Api.GetCode(weChatConfig.WeixinCorpId, strBackUrl, Server.UrlEncode(Request.RawUrl));
                    log.Debug(strUrl);

                    if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                    {
                        AjaxResult <int> result = new AjaxResult <int>();
                        result.Message       = new JsonMessage((int)HttpStatusCode.Unauthorized, strUrl);
                        filterContext.Result = Json(result, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        log.Debug("filterContext.Result = new RedirectResult(strUrl) : " + strUrl);
                        filterContext.Result = new RedirectResult(strUrl);
                    }
                    return(string.Empty);
                }
            }
            return(string.Empty);
        }
示例#25
0
        public string GetCode(string urlEncode)
        {
            var code = OAuth2Api.GetCode(workSetting.Value.CorpId, urlEncode, "", workSetting.Value.LoginAppId);

            return(code);
        }