如何实现.NET Core企业微信网页授权登录功能?

2026-03-30 10:161阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计1348个文字,预计阅读时间需要6分钟。

如何实现.NET Core企业微信网页授权登录功能?

目录

1.开发前准备

- 参数获取

2.企业微信OAuth2接入流程

3.构造网页授权链接

4.调用代码部分

4.1 appsettings配置 4.2 配置IHttpClientFactory调用微信客户端 4.3 类准备 4.4 方法准备 4.5 调用

目录
  • 1.开发前准备
    • 参数获取
  • 2.企业微信OAuth2接入流程
    • 3.构造网页授权链接
      • 4. 调用代码部分
        • 4.1 appsettings配置
        • 4.2 配置IHttpClientFactory调用微信客户端
        • 4.3 类准备
        • 4.4方法准备
        • 4.5调用
      • 5.截图

        1.开发前准备

        参数获取

        corpid

        每个企业都拥有唯一的corpid,获取此信息可在管理后台“我的企业”-“企业信息”下查看“企业ID”

        secret

        secret是企业应用里面用于保障数据安全的“钥匙”,每一个应用都有一个独立的访问密钥,为了保证数据的安全,secret务必不能泄漏。

        框架

        例子使用yishaadmin开源框架为例

        如何实现.NET Core企业微信网页授权登录功能?

        2.企业微信OAuth2接入流程

        第一步: 用户点击连接

        第二步: Index页取得回调Code

        第三步: 根据Code和access_token获取UserID

        第四步: 根据UserID到通讯录接口获取其他信息

        3.构造网页授权链接

        假定当前企业CorpID:wxCorpId
        访问链接:api.3dept.com/cgi-bin/query?action=get

        根据URL规范,将上述参数分别进行UrlEncode,得到拼接的OAuth2链接为:

        open.weixin.qq.com/connect/oauth2/authorize?appid=wxCorpId&redirect_uri=developer.work.weixin.qq.com/document/path/91335

        4. 调用代码部分

        4.1 appsettings配置

        "Wx": { "corpid": "", "corpsecret": "", "baseurl": "qyapi.weixin.qq.com", "getUserByCode": "/cgi-bin/user/getuserinfo?access_token={0}&code={1}", "getToken": "/cgi-bin/gettoken?corpid={0}&corpsecret={1}", "getUserByUserId": "/cgi-bin/user/get?access_token={0}&userid={1}" }

        4.2 配置IHttpClientFactory调用微信客户端

        public static IHttpClientFactory developer.work.weixin.qq.com/document/path/91039

        /// <summary> /// 获取Token /// </summary> /// <returns>Item1 Token;Item2 是否成功</returns> public Tuple<string,bool> GetToken() { //判断Token是否存在 以及Token是否在有效期内 if(string.IsNullOrEmpty(ApplicationContext.Token) || ApplicationContext.TimeOutDate > DateTime.Now) { //构造请求链接 var requestBuild = GlobalContext.Configuration["Wx:getToken"]; requestBuild = string.Format(requestBuild, GlobalContext.Configuration["Wx:corpid"], GlobalContext.Configuration["Wx:corpsecret"] ); using (var wxClient = GlobalContext.developer.work.weixin.qq.com/document/path/91023

        /// <summary> /// 获取用户ID /// </summary> /// <param name="token">企业微信Token</param> /// <param name="code">构造请求的回调code</param> /// <returns>Item1 UserId;Item2 是否成功</returns> public Tuple<string, bool> GetUserID(string token,string code) { //构造请求链接 var requestBuild = GlobalContext.Configuration["Wx:getUserByCode"]; requestBuild = string.Format(requestBuild,token,code); using (var wxClient = GlobalContext.developer.work.weixin.qq.com/document/path/90196

        /// <summary> /// 获取用户通讯录 /// </summary> /// <returns>Item1 头像,获取失败时为错误信息;Item2 名称;Item3 是否成功</returns> public Tuple<string,string, bool> GetUserByID(string token, string userid) { //构造请求链接 var requestBuild = GlobalContext.Configuration["Wx:getUserByUserId"]; requestBuild = string.Format(requestBuild, token, userid); //建立HttpClient using (var wxClient = GlobalContext.httpClientFactory.CreateClient("WxClient")) { var httpResponse = wxClient.GetAsync(requestBuild).Result; if (httpResponse.StatusCode == System.Net.HttpStatusCode.OK) { var dynamic = JsonConvert.DeserializeObject<GetUserResult>( httpResponse.Content.ReadAsStringAsync().Result ); return Tuple.Create(dynamic.avatar, dynamic.name, true); } else { return Tuple.Create("获取用户ID失败,请稍后重试!","", false); } } }

        4.5调用

        本方法是为了企业微信登录时绕过用户登录直接使用企业微信用户登录,有其他需求根据需要调整。

        主页index 中使用code参数获取回调传进来的code,调用GetToken方法获取Token,然后根据Token和Code获取UserID,最后根据UserID和Token获取通讯录的头像和名称。需要注意的是我们要对每个用户最新的code进行缓存,在企业微信内部浏览器时刷新code参数不会变动,但是code只能使用一次会导致接口调用失败。

        [HttpGet] public async Task<IActionResult> Index(string code) { OperatorInfo operatorInfo = default; TData<List<MenuEntity>> objMenu = await menuBLL.GetList(null); List<MenuEntity> menuList = objMenu.Data; menuList = menuList.Where(p => p.MenuStatus == StatusEnum.Yes.ParseToInt()).ToList(); if (code != null)//企业微信登录 { //获取联系人 从内存中取||从接口取 string username, portrait = default; bool issuccess2 = default; //缓存最近的一次code 用于刷新URL时重复code请求失败 var codeCache = ApplicationContext.UserCache.FirstOrDefault(o => o.Code == code); if(codeCache == null) { //获取token Token时间为过期时间减5分钟 var (token, issuccess) = GetToken(); if (!issuccess) return RedirectToAction("error1", new { errormessage = token }); //获取userid var (userid, issuccess1) = GetUserID(token, code); if (!issuccess1) return RedirectToAction("error1", new { errormessage = userid }); var useridCache = ApplicationContext.UserCache.FirstOrDefault(o => o.UserID == userid); if (useridCache == null)//不存在缓存中 { (portrait, username, issuccess2) = GetUserByID(token, userid); if (!issuccess2) return RedirectToAction("error1", new { errormessage = portrait }); //加缓存 ApplicationContext.UserCache.Add(new UserCache() { Code = code, Username = username, Portrait = portrait, UserID = userid }); //保存登录日志 var log = logLoginBLL.SaveForm(new LogLoginEntity { Remark = username, ExtraRemark = token + ":" + userid }); } else//从缓存中获取用户信息 { username = useridCache.Username; portrait = useridCache.Portrait; //更新最新code useridCache.Code = code; } } else { username = codeCache.Username; portrait = codeCache.Portrait; } //模拟登录 TData<UserEntity> userObj = await userBLL.CheckLogin(ApplicationContext.WxUser , ApplicationContext.WxPassWord , (int)PlatformEnum.Web); if (userObj.Tag == 1) { await new UserBLL().UpdateUser(userObj.Data); await Operator.Instance.AddCurrent(userObj.Data.WebToken); var op = await Operator.Instance.Current(); AuthorizeListWhere(op); } //构建前端返回的用户名 以及头像 operatorInfo = new OperatorInfo(); operatorInfo.RealName = username; operatorInfo.UserName = username; operatorInfo.Portrait = portrait; } else//正常网页登录 { operatorInfo = await Operator.Instance.Current(); if (operatorInfo == null) return RedirectToAction("Login"); if (operatorInfo.IsSystem != 1) { AuthorizeListWhere(operatorInfo); } } //授权筛选 void AuthorizeListWhere(OperatorInfo info) { TData<List<MenuAuthorizeInfo>> objMenuAuthorize = menuAuthorizeBLL.GetAuthorizeList(info).Result; List<long?> authorizeMenuIdList = objMenuAuthorize.Data.Select(p => p.MenuId).ToList(); menuList = menuList.Where(p => authorizeMenuIdList.Contains(p.Id)).ToList(); } new CookieHelper().WriteCookie("UserName", operatorInfo.UserName, false); new CookieHelper().WriteCookie("RealName", operatorInfo.RealName, false); ViewBag.OperatorInfo = operatorInfo; ViewBag.MenuList = menuList; return View(); }

        Index.Html调整

        5.截图

        到此这篇关于.NET Core企业微信网页授权登录的实现的文章就介绍到这了,更多相关.NET Core企业微信授权登录内容请搜索自由互联以前的文章或继续浏览下面的相关文章希望大家以后多多支持自由互联!

        标签:实现

        本文共计1348个文字,预计阅读时间需要6分钟。

        如何实现.NET Core企业微信网页授权登录功能?

        目录

        1.开发前准备

        - 参数获取

        2.企业微信OAuth2接入流程

        3.构造网页授权链接

        4.调用代码部分

        4.1 appsettings配置 4.2 配置IHttpClientFactory调用微信客户端 4.3 类准备 4.4 方法准备 4.5 调用

        目录
        • 1.开发前准备
          • 参数获取
        • 2.企业微信OAuth2接入流程
          • 3.构造网页授权链接
            • 4. 调用代码部分
              • 4.1 appsettings配置
              • 4.2 配置IHttpClientFactory调用微信客户端
              • 4.3 类准备
              • 4.4方法准备
              • 4.5调用
            • 5.截图

              1.开发前准备

              参数获取

              corpid

              每个企业都拥有唯一的corpid,获取此信息可在管理后台“我的企业”-“企业信息”下查看“企业ID”

              secret

              secret是企业应用里面用于保障数据安全的“钥匙”,每一个应用都有一个独立的访问密钥,为了保证数据的安全,secret务必不能泄漏。

              框架

              例子使用yishaadmin开源框架为例

              如何实现.NET Core企业微信网页授权登录功能?

              2.企业微信OAuth2接入流程

              第一步: 用户点击连接

              第二步: Index页取得回调Code

              第三步: 根据Code和access_token获取UserID

              第四步: 根据UserID到通讯录接口获取其他信息

              3.构造网页授权链接

              假定当前企业CorpID:wxCorpId
              访问链接:api.3dept.com/cgi-bin/query?action=get

              根据URL规范,将上述参数分别进行UrlEncode,得到拼接的OAuth2链接为:

              open.weixin.qq.com/connect/oauth2/authorize?appid=wxCorpId&redirect_uri=developer.work.weixin.qq.com/document/path/91335

              4. 调用代码部分

              4.1 appsettings配置

              "Wx": { "corpid": "", "corpsecret": "", "baseurl": "qyapi.weixin.qq.com", "getUserByCode": "/cgi-bin/user/getuserinfo?access_token={0}&code={1}", "getToken": "/cgi-bin/gettoken?corpid={0}&corpsecret={1}", "getUserByUserId": "/cgi-bin/user/get?access_token={0}&userid={1}" }

              4.2 配置IHttpClientFactory调用微信客户端

              public static IHttpClientFactory developer.work.weixin.qq.com/document/path/91039

              /// <summary> /// 获取Token /// </summary> /// <returns>Item1 Token;Item2 是否成功</returns> public Tuple<string,bool> GetToken() { //判断Token是否存在 以及Token是否在有效期内 if(string.IsNullOrEmpty(ApplicationContext.Token) || ApplicationContext.TimeOutDate > DateTime.Now) { //构造请求链接 var requestBuild = GlobalContext.Configuration["Wx:getToken"]; requestBuild = string.Format(requestBuild, GlobalContext.Configuration["Wx:corpid"], GlobalContext.Configuration["Wx:corpsecret"] ); using (var wxClient = GlobalContext.developer.work.weixin.qq.com/document/path/91023

              /// <summary> /// 获取用户ID /// </summary> /// <param name="token">企业微信Token</param> /// <param name="code">构造请求的回调code</param> /// <returns>Item1 UserId;Item2 是否成功</returns> public Tuple<string, bool> GetUserID(string token,string code) { //构造请求链接 var requestBuild = GlobalContext.Configuration["Wx:getUserByCode"]; requestBuild = string.Format(requestBuild,token,code); using (var wxClient = GlobalContext.developer.work.weixin.qq.com/document/path/90196

              /// <summary> /// 获取用户通讯录 /// </summary> /// <returns>Item1 头像,获取失败时为错误信息;Item2 名称;Item3 是否成功</returns> public Tuple<string,string, bool> GetUserByID(string token, string userid) { //构造请求链接 var requestBuild = GlobalContext.Configuration["Wx:getUserByUserId"]; requestBuild = string.Format(requestBuild, token, userid); //建立HttpClient using (var wxClient = GlobalContext.httpClientFactory.CreateClient("WxClient")) { var httpResponse = wxClient.GetAsync(requestBuild).Result; if (httpResponse.StatusCode == System.Net.HttpStatusCode.OK) { var dynamic = JsonConvert.DeserializeObject<GetUserResult>( httpResponse.Content.ReadAsStringAsync().Result ); return Tuple.Create(dynamic.avatar, dynamic.name, true); } else { return Tuple.Create("获取用户ID失败,请稍后重试!","", false); } } }

              4.5调用

              本方法是为了企业微信登录时绕过用户登录直接使用企业微信用户登录,有其他需求根据需要调整。

              主页index 中使用code参数获取回调传进来的code,调用GetToken方法获取Token,然后根据Token和Code获取UserID,最后根据UserID和Token获取通讯录的头像和名称。需要注意的是我们要对每个用户最新的code进行缓存,在企业微信内部浏览器时刷新code参数不会变动,但是code只能使用一次会导致接口调用失败。

              [HttpGet] public async Task<IActionResult> Index(string code) { OperatorInfo operatorInfo = default; TData<List<MenuEntity>> objMenu = await menuBLL.GetList(null); List<MenuEntity> menuList = objMenu.Data; menuList = menuList.Where(p => p.MenuStatus == StatusEnum.Yes.ParseToInt()).ToList(); if (code != null)//企业微信登录 { //获取联系人 从内存中取||从接口取 string username, portrait = default; bool issuccess2 = default; //缓存最近的一次code 用于刷新URL时重复code请求失败 var codeCache = ApplicationContext.UserCache.FirstOrDefault(o => o.Code == code); if(codeCache == null) { //获取token Token时间为过期时间减5分钟 var (token, issuccess) = GetToken(); if (!issuccess) return RedirectToAction("error1", new { errormessage = token }); //获取userid var (userid, issuccess1) = GetUserID(token, code); if (!issuccess1) return RedirectToAction("error1", new { errormessage = userid }); var useridCache = ApplicationContext.UserCache.FirstOrDefault(o => o.UserID == userid); if (useridCache == null)//不存在缓存中 { (portrait, username, issuccess2) = GetUserByID(token, userid); if (!issuccess2) return RedirectToAction("error1", new { errormessage = portrait }); //加缓存 ApplicationContext.UserCache.Add(new UserCache() { Code = code, Username = username, Portrait = portrait, UserID = userid }); //保存登录日志 var log = logLoginBLL.SaveForm(new LogLoginEntity { Remark = username, ExtraRemark = token + ":" + userid }); } else//从缓存中获取用户信息 { username = useridCache.Username; portrait = useridCache.Portrait; //更新最新code useridCache.Code = code; } } else { username = codeCache.Username; portrait = codeCache.Portrait; } //模拟登录 TData<UserEntity> userObj = await userBLL.CheckLogin(ApplicationContext.WxUser , ApplicationContext.WxPassWord , (int)PlatformEnum.Web); if (userObj.Tag == 1) { await new UserBLL().UpdateUser(userObj.Data); await Operator.Instance.AddCurrent(userObj.Data.WebToken); var op = await Operator.Instance.Current(); AuthorizeListWhere(op); } //构建前端返回的用户名 以及头像 operatorInfo = new OperatorInfo(); operatorInfo.RealName = username; operatorInfo.UserName = username; operatorInfo.Portrait = portrait; } else//正常网页登录 { operatorInfo = await Operator.Instance.Current(); if (operatorInfo == null) return RedirectToAction("Login"); if (operatorInfo.IsSystem != 1) { AuthorizeListWhere(operatorInfo); } } //授权筛选 void AuthorizeListWhere(OperatorInfo info) { TData<List<MenuAuthorizeInfo>> objMenuAuthorize = menuAuthorizeBLL.GetAuthorizeList(info).Result; List<long?> authorizeMenuIdList = objMenuAuthorize.Data.Select(p => p.MenuId).ToList(); menuList = menuList.Where(p => authorizeMenuIdList.Contains(p.Id)).ToList(); } new CookieHelper().WriteCookie("UserName", operatorInfo.UserName, false); new CookieHelper().WriteCookie("RealName", operatorInfo.RealName, false); ViewBag.OperatorInfo = operatorInfo; ViewBag.MenuList = menuList; return View(); }

              Index.Html调整

              5.截图

              到此这篇关于.NET Core企业微信网页授权登录的实现的文章就介绍到这了,更多相关.NET Core企业微信授权登录内容请搜索自由互联以前的文章或继续浏览下面的相关文章希望大家以后多多支持自由互联!

              标签:实现