예제 #1
0
        public ActionResult SignIn(string code, string state)
        {
            try
            {
                if (string.IsNullOrEmpty(code))
                {
                    return(Redirect("/pages/error/error.html"));
                }

                var token = CommonApi.GetToken(WeixinWorkHelper.CorpId, WeixinWorkHelper.AgentSecrets[_agentid]);
                if (token.errcode != 0)
                {
                    return(Redirect("/pages/error/error.html"));
                }

                GetUserInfoResult result = OAuth2Api.GetUserId(token.access_token, code);
                if (result.errcode != 0)
                {
                    return(Redirect("/pages/error/error.html"));
                }

                SysUser user = dbContext.Set <SysUser>().Where(x => x.UserCode == result.UserId).FirstOrDefault();
                if (user == null)
                {
                    //没有账号:根据业务调整
                    return(Redirect("/pages/error/error.html"));
                }

                SSOClient.SignIn(user.UserId);
                return(ToMenu(state));
            }
            catch (Exception ex)
            {
                LogHelper.SaveLog(ex);
                return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" }));
            }
        }
예제 #2
0
        public IActionResult UserInfoCallback(string code, string returnUrl)
        {
            if (string.IsNullOrWhiteSpace(code))
            {
                return(RedirectToAction("Index", "Error", new { title = "无效访问", message = "您的请求参数不合法,请从正规渠道访问此功能。" }));
            }

            try
            {
                var token = AccessTokenContainer.TryGetToken(_corpId, _secret);
                if (string.IsNullOrWhiteSpace(token))
                {
                    //_log.Error("获取ACCESSTOKEN详情失败:AccessTokenContainer.TryGetToken()获取失败");
                    return(RedirectToAction("Index", "Error", new { title = "访问失败", message = "从微信服务端请求数据失败,请稍候再试。" }));
                }

                var user = OAuth2Api.GetUserId(token, code);
                if (user.errcode != Senparc.Weixin.ReturnCode_Work.请求成功)
                {
                    //_log.Error("获取用户ID失败:" + user.errmsg);
                    return(RedirectToAction("Index", "Error", new { title = "加载失败", message = "从微信服务端获取用户信息失败,请联系管理员或稍候再试" }));
                }

                if (string.IsNullOrWhiteSpace(user.UserId))
                {
                    //_log.Error("获取用户ID失败,接口调用成功,但USERID为空:" + JsonConvert.SerializeObject(user));
                    return(RedirectToAction("Index", "Error", new { title = "拒绝访问", message = "仅限企业微信内部员工使用,未能获取到您的数据,请联系管理员" }));
                }
                else
                {
                    var db      = MyDb.New();
                    var appUser = db.Load <AppUser>(a => a.No == user.UserId);

                    if (appUser == null)
                    {
                        return(RedirectToAction("Index", "Error", new { title = "访问失败", message = "无权访问,请联系管理员" }));
                    }
                    else
                    {
                        var dto = new UserDto {
                            No = appUser.No, Name = appUser.Name, DepartmentId = appUser.DepartmentId
                        };
                        if (appUser.IsFinance)
                        {
                            dto.Role = "audit";
                        }
                        else
                        {
                            dto.Role = appUser.IsMaster ? "master" : "user";
                        }

                        var claims = new List <Claim>
                        {
                            new Claim(ClaimTypes.NameIdentifier, dto.No),
                            new Claim(ClaimTypes.Name, dto.Name),
                            new Claim(ClaimTypes.Role, dto.Role),
                            new Claim("Department", dto.DepartmentId.ToString())
                        };

                        HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                        HttpContext.SignInAsync(
                            new ClaimsPrincipal(
                                new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme)
                                )
                            );

                        return(Redirect(returnUrl));
                    }
                }
            }
            catch (Exception ex)
            {
                //_log.Error(ex);
                return(RedirectToAction("Index", "Error", new { title = "访问失败", message = "系统错误:" + ex.Message + ",请联系管理员" }));
            }
        }
예제 #3
0
 public static GetUserInfoResult GetUserId(string code)
 {
     return(OAuth2Api.GetUserId(GetToken(), code));
 }
        public async Task <ActionResult> BackLogin()
        {
            string returnUrl = Session["ReturnUrl"] as string;

            try
            {
                log.Error("Entering BackLogin, returnUrl=" + returnUrl);
                //ViewBag.ReturnUrl = returnUrl;
                if (Request["code"] != null)
                {
                    string code     = Request["code"].ToString();
                    string wechatid = Request["wechatid"].ToString();

                    log.Debug("code:" + code + " wechatid:" + wechatid);

                    SysUser user = null;

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

                    if (weChatConfig.IsCorp.HasValue && !weChatConfig.IsCorp.Value)
                    {
                        var code1 = Innocellence.Weixin.MP.AdvancedAPIs.OAuthApi.GetAccessToken(weChatConfig.WeixinCorpId, weChatConfig.WeixinCorpSecret, code);

                        IWechatMPUserService ser = EngineContext.Current.Resolve <IWechatMPUserService>();

                        WechatMPUser objUser = null;

                        objUser = ser.Repository.Entities.Where(a => a.OpenId == code1.openid).FirstOrDefault();

                        log.Debug("MP objUser:"******"N" : "U") + " OpenID:" + code1.openid);

                        //如果用户不存在就添加用户

                        if (objUser == null)
                        {
                            // var userinfo = Innocellence.Weixin.MP.AdvancedAPIs.UserApi.Info(weChatConfig.WeixinCorpId, weChatConfig.WeixinCorpSecret, code1.openid);
                            // objUser = WechatMPUserView.ConvertWeChatUserToMpUser(userinfo, weChatConfig.AccountManageId.Value, weChatConfig.Id);
                            // ser.Repository.Insert(objUser);
                            lock (StaticLockObj)                                                                         //防止插入多条数据
                            {
                                objUser = ser.Repository.Entities.Where(a => a.OpenId == code1.openid).FirstOrDefault(); //为什么要重新查一次??因为有lock
                                if (objUser == null)
                                {
                                    WeChatCommonService.SycUserFromWeixinMP(code1.openid, ref objUser, weChatConfig);
                                }
                            }
                        }


                        if (objUser == null || objUser.IsCanceled == true || objUser.SubScribe == 0) //未关注
                        {
                            log.Debug("未关注 OpenID:{0}", code1.openid);
                            user = new SysUser()
                            {
                                UserName     = code1.openid,
                                WeChatUserID = "",
                                Id           = 0,
                                Apps         = new System.Collections.Generic.List <int>()
                                {
                                    int.Parse(wechatid)
                                }
                            };
                        }
                        else //已关注
                        {
                            user = new SysUser()
                            {
                                UserName     = objUser.NickName,
                                WeChatUserID = objUser.OpenId,
                                Id           = objUser.Id,
                                Apps         = new System.Collections.Generic.List <int>()
                                {
                                    int.Parse(wechatid)
                                }
                            };
                        }


                        //var user = UserManager.Entities.FirstOrDefault(a => a.UserName == code1.UserId);
                    }
                    else
                    {
                        var Token = AccessTokenContainer.TryGetToken(weChatConfig.WeixinCorpId, weChatConfig.WeixinCorpSecret);
                        log.Error("Token:" + Token);
                        var code1 = OAuth2Api.GetUserId(Token, code);

                        // BaseService<SysAddressBookMember> ser = new BaseService<SysAddressBookMember>();
                        IAddressBookService ser = EngineContext.Current.Resolve <IAddressBookService>();

                        if (string.IsNullOrEmpty(code1.UserId)) //没关注
                        {
                            user = new SysUser()
                            {
                                UserName     = code1.OpenId,
                                WeChatUserID = "",
                                Id           = 0,
                                Apps         = new System.Collections.Generic.List <int>()
                                {
                                    int.Parse(wechatid)
                                }
                            };
                        }
                        else //已经关注
                        {
                            var objUser = ser.Repository.Entities.Where(a => a.UserId == code1.UserId && a.DeleteFlag != 1).FirstOrDefault();

                            log.Debug("objUser:{1} UserID:{0} Status:{2}", code1.UserId, (objUser == null ? "N" : "U"), objUser == null ? "" : objUser.EmployeeStatus);

                            if (objUser != null && (objUser.EmployeeStatus == "D" || objUser.EmployeeStatus == "U")) //离职或状态不明
                            {
                                user = new SysUser()
                                {
                                    UserName     = objUser.UserId,
                                    WeChatUserID = "",
                                    Id           = 0,
                                    Apps         = new System.Collections.Generic.List <int>()
                                    {
                                        int.Parse(wechatid)
                                    }
                                };
                            }
                            else  //已经关注
                            {
                                //objUser = new SysAddressBookMember() { UserId = code1.UserId, Id = 0 };
                                if (objUser == null)
                                {
                                    lock (StaticLockObjMP)   //防止插入多条数据
                                    {
                                        if (objUser == null) //lock后,重新查一次
                                        {
                                            objUser = ser.Repository.Entities.Where(a => a.UserId == code1.UserId).FirstOrDefault();
                                        }


                                        WeChatCommonService.SyncUserFromWechat(code1.UserId, ref objUser, weChatConfig);
                                    }
                                }
                                user = new SysUser()
                                {
                                    UserName     = objUser.UserName,
                                    WeChatUserID = objUser.UserId,
                                    Id           = objUser.Id,
                                    Apps         = new System.Collections.Generic.List <int>()
                                    {
                                        int.Parse(wechatid)
                                    }
                                };
                            }
                        }



                        //var user = UserManager.Entities.FirstOrDefault(a => a.UserName == code1.UserId);
                    }

                    log.Debug("SignInNoDB UserID:{0} User:{1}", user.Id, user.UserName);


                    await _authenticationService.SignInNoDB(user, true);

                    //return Redirect(returnUrl);

                    ////////登录日志
                    //////BaseService<Logs> objServLogs = new BaseService<Logs>();
                    //////objServLogs.Insert(new Logs() { LogCate = "WechatLogin", LogContent = "登录成功", CreatedUserID = objUser.WeChatUserID, CreatedUserName = objUser.WeChatUserID });
                }

                //LogManager.GetLogger(this.GetType()).Error("strUrl:" + strUrl);

                var Ret = returnUrl + (returnUrl.IndexOf("?") > 0 ? "&_Callback=1" : "?_Callback=1");
                log.Debug("Ret URL:{0}", Ret);

                return(Redirect(Ret));
            }
            catch (Exception ex)
            {
                LogManager.GetLogger(this.GetType()).Error(ex, ex.Message);
                return(Redirect("/noCropPermission.html"));
            }

            //  View();
        }
예제 #5
0
 public void Post(string code, string state)
 {
     var accessToken = AccessTokenContainer.GetToken(corpId, appSecret);
     var result      = OAuth2Api.GetUserId(accessToken, code);
 }
예제 #6
0
        public ActionResult OAuth2Callback(string corpid, string accesstoken, string scope, string reurl, string code, string state)
        {
            //LogWriter.Info("OAuth2Callback:");
            string url = reurl ?? "";

            url = Base64Helper.DecodeBase64(url.Replace(" ", "+"));

            if (string.IsNullOrEmpty(code))
            {
                LogWriter.Info(string.Format("qyid为“{0}”的OAuth2授权失败,原因:拒绝了授权", corpid));
                return(Content("您拒绝了授权!"));
            }

            if (state != "JeffreySu" && state != "JeffreSu?10000skip=true")
            {
                //这里的state其实是会暴露给客户端的,验证能力很弱,这里只是演示一下
                //实际上可以存任何想传递的数据,比如用户ID,并且需要结合例如下面的Session["OAuthAccessToken"]进行验证
                LogWriter.Info(string.Format("qyid为“{0}”的OAuth2授权失败,原因:验证失败", corpid));
                return(Content("验证失败!请从正规途径进入!"));
            }


            #region 校验
            if (string.IsNullOrEmpty(reurl))
            {
                LogWriter.Info(string.Format("qyid为“{0}”的OAuth2Base获取失败,原因:reurl为空", corpid));
                return(Content("非法访问"));
            }
            var account = GetAccount(corpid);
            if (account == null)
            {
                LogWriter.Info(string.Format("qyid为“{0}”的OAuth2Base获取失败,原因:企业号不存在", corpid));
                return(Content("非法访问"));
            }
            var passtoken = GetPassToken(account, accesstoken);
            if (passtoken == null)
            {
                LogWriter.Info(string.Format("qyid为“{0}”的OAuth2Base获取失败,原因:accesstoken错误", corpid));
                return(Content("非法访问"));
            }
            if (!ValidateOauth2Domain(passtoken, reurl))
            {
                LogWriter.Info(string.Format("qyid为“{0}”的OAuth2Base获取失败,原因:reurl{1}错误", corpid, reurl));
                return(Content("非法访问"));
            }
            #endregion

            //通过,用code换取access_token
            GetUserInfoResult result = null;
            var wxFO = Formula.FormulaHelper.CreateFO <WxFO>();
            try
            {
                result = OAuth2Api.GetUserId(wxFO.GetAccessToken(corpid), code);
                //LogWriter.Info("OAuth2Callback:GetUserId" + JsonHelper.ToJson(result));
            }
            catch (Exception ex)
            {
                LogWriter.Error(ex, string.Format("qyid为{0}的静默授权在通过code获取token时异常", corpid));
                result = OAuth2Api.GetUserId(wxFO.GetAccessToken(corpid, true), code);
            }
            if (result.errcode != ReturnCode_QY.请求成功)
            {
                LogWriter.Info(string.Format("qyid为{0}的静默授权在通过code获取token时异常,原因:{1}", corpid, result.errmsg));
                return(Content("错误:" + result.errmsg));
            }
            if (!string.IsNullOrEmpty(result.user_ticket) && !string.IsNullOrEmpty(result.UserId) && (scope == "snsapi_userinfo" || scope == "snsapi_privateinfo"))
            {
                GetUserDetailResult resultDetail = null;
                try
                {
                    resultDetail = CommonJsonSend.Send <GetUserDetailResult>(wxFO.GetAccessToken(corpid), "https://qyapi.weixin.qq.com/cgi-bin/user/getuserdetail?access_token={0}",
                                                                             new {
                        user_ticket = result.user_ticket,
                    });
                    //LogWriter.Info("OAuth2Callback:Send" + JsonHelper.ToJson(resultDetail));
                }
                catch (Exception ex)
                {
                    LogWriter.Error(ex, string.Format("qyid为{0}的认证授权在通过ticket获取详情时异常", corpid));
                }
                if (resultDetail != null && resultDetail.userid != null)
                {
                    url = string.Format("{0}{1}userinfo={2}"
                                        , url, url.Contains('?') ? "&" : "?", Base64Helper.EncodeBase64(JsonHelper.ToJson(new {
                        userid     = result.UserId,
                        openid     = result.OpenId,
                        name       = resultDetail.name,
                        department = resultDetail.department,
                        position   = resultDetail.position,
                        mobile     = resultDetail.mobile,
                        gender     = resultDetail.gender,
                        email      = resultDetail.email,
                        avatar     = resultDetail.avatar,
                    })));
                    //LogWriter.Info("OAuth2Callback:url1:" + url);
                    return(Redirect(url));
                }
            }

            url = string.Format("{0}{1}userinfo={2}"
                                , url, url.Contains('?') ? "&" : "?", Base64Helper.EncodeBase64(JsonHelper.ToJson(new { userid = result.UserId, openid = result.OpenId })));
            //LogWriter.Info("OAuth2Callback:url2:" + url);
            return(Redirect(url));
        }
 public string GetUserId(string accessToken, string code)
 {
     return(OAuth2Api.GetUserId(accessToken, code).UserId);
 }
예제 #8
0
        public IActionResult UserInfoCallback(string code, string returnUrl)
        {
            if (string.IsNullOrWhiteSpace(code))
            {
                return(RedirectToAction("Error", new { title = "无效访问", message = "您的请求参数不合法,请从正规渠道访问此功能。" }));
            }

            try
            {
                var token = AccessTokenContainer.TryGetToken(_corpId, _secret);
                if (string.IsNullOrWhiteSpace(token))
                {
                    _log.Error("获取ACCESSTOKEN详情失败:AccessTokenContainer.TryGetToken()获取失败");
                    return(RedirectToAction("Error", new { title = "访问失败", message = "从微信服务端请求数据失败,请稍候再试。" }));
                }

                var user = OAuth2Api.GetUserId(token, code);
                if (user.errcode != Senparc.Weixin.ReturnCode_Work.请求成功)
                {
                    _log.Error("获取用户ID失败:" + user.errmsg);
                    return(RedirectToAction("Error", new { title = "加载失败", message = "从微信服务端获取用户信息失败,请联系管理员或稍候再试" }));
                }

                if (string.IsNullOrWhiteSpace(user.UserId))
                {
                    _log.Error("获取用户ID失败,接口调用成功,但USERID为空:" + JsonConvert.SerializeObject(user));
                    return(RedirectToAction("Error", new { title = "拒绝访问", message = "仅限企业微信内部员工使用,未能获取到您的数据,请联系管理员" }));
                }
                else
                {
                    var userInfo = _userUtil.Get(user.UserId);
                    if (userInfo != null)
                    {
                        var userName = userInfo.name;

                        var deptId = 0;
                        if (userInfo.department.Length > 0)
                        {
                            deptId = (int)userInfo.department.Max();
                        }

                        var dept = _deptUtil.Get(deptId);
                        if (dept == null)
                        {
                            _log.Error("获取部门失败,用户消息:" + string.Join(',', userInfo.department));
                            return(RedirectToAction("Error", new { title = "访问失败", message = "获取部门数据失败,请联系管理员" }));
                        }

                        var userDto = new WeixinUser
                        {
                            UserId   = userInfo.userid.ToLower(),
                            UserName = userInfo.name,
                            DeptId   = deptId,
                            DeptName = dept.name
                        };

                        var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, "WeixinUserName", ClaimTypes.Role);

                        identity.AddClaim(new Claim("WeixinUserId", user.UserId));
                        identity.AddClaim(new Claim("WeixinUserName", userName));
                        identity.AddClaim(new Claim("WeixinDeptId", dept.id.ToString()));
                        identity.AddClaim(new Claim("WeixinDeptName", dept.name));
                        identity.AddClaim(new Claim(ClaimTypes.Role, "Weixin"));

                        var principal = new ClaimsPrincipal(identity);
                        HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                        HttpContext.SignInAsync(principal, new AuthenticationProperties
                        {
                            IsPersistent = true,
                            RedirectUri  = "/OAuth2/Index"
                        });

                        HttpContext.Session.Set("WeixinUser", userDto);
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        _log.Error("获取用户详情失败:缓存中不存在此");
                        return(RedirectToAction("Error", new { title = "无效访问", message = "仅限企业微信内部员工使用,若您加入企业,请联系管理员" }));
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex);
                return(RedirectToAction("Error", new { title = "访问失败", message = "系统错误:" + ex.Message + ",请联系管理员" }));
            }
        }