3. ABP .NETCore 添加企业微信第三方登录

1.企业微信登录步骤

  1.获取企业微信Token  

      官方文档:https://work.weixin.qq.com/api/doc#90000/90135/91039

       2.通过Token 与前端传的Code 参数 调用微信API获取 访问用户身份

      官方文档https://work.weixin.qq.com/api/doc#90000/90135/91023

       3.通过获取的企业用户信息到自己的服务器进行查询,存在就登录成功,不存在则登录失败,前提是我们先要把企业微信的用户同步到自己的服务器。

 

 

2.下图是我们需要添加或修改的文件

3. ABP .NETCore 添加企业微信第三方登录_第1张图片

 

 

 

 

 

 3下面开始我们的代码:

1.先声明微信接口返回的实体

// 获取Token返回的实体
public
class WeChatToken { public int errcode { get; set; } public string errmsg { get; set; } public string access_token { get; set; } public int expires_in { get; set; } }
public class WeChatUserInfo
 {
        public int errcode { get; set; }
        public string errmsg { get; set; }
        // 企业用户ID
        public string UserId { get; set; } 
        // 非企业用户ID
        public string OpenId { get; set; }        
        public string DeviceId { get; set; }
}

2.添加企业微信第三方登录

using Abp.UI;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using TexHong_EMWX.Authentication.JwtBearer;
using TexHong_EMWX.Authorization;
using TexHong_EMWX.Authorization.Users;
using TexHong_EMWX.Models.WeChat;
using TexHong_EMWX.WXUsers;

namespace TexHong_EMWX.Authentication.External
{
    public class WechatMiniProgramAuthProviderApi : ExternalAuthProviderApiBase
    {
        ///  第三方登录名称需要与前端配置的一致
        public const string ProviderName = "EnterpriseWechat";
        private readonly UserManager _userManager;
     /// 本地微信用户的服务。 这个需要自己添加。用于判断当前微信用户是否有权限
private readonly WXUserManager _wXUserManager; private readonly LogInManager _logInManager; private readonly TokenAuthConfiguration _configuration; private readonly IExternalAuthConfiguration _externalAuthConfiguration; public WechatMiniProgramAuthProviderApi( UserManager _userManager, WXUserManager _wXUserManager, LogInManager _logInManager, TokenAuthConfiguration _configuration, IExternalAuthConfiguration _externalAuthConfiguration) { this._userManager = _userManager; this._wXUserManager = _wXUserManager; this._logInManager = _logInManager; this._configuration = _configuration; this._externalAuthConfiguration = _externalAuthConfiguration; } public override async Task GetUserInfo(string Code) {
       // 1. 获取企业微信ToKen WeChatToken weChatToken
= await this.GetWechatToKen();
// 2. 获取用户信息 WeChatUserInfo weChatUserInfo
= await this.GetWechatUserId(Code, weChatToken.access_token);
// 3. 通过获取的的微信用户UserId并判断是否存在自己的服务器中。 WXUser wXUser
= await _wXUserManager.FindByUserId(weChatUserInfo.UserId); var t = wXUser == null ? new ExternalAuthUserInfo() : new ExternalAuthUserInfo { EmailAddress = wXUser.Email, Surname = wXUser.AbpUser.Surname, ProviderKey = weChatUserInfo.UserId, Provider = ProviderName, Name = wXUser.AbpUser.Name }; return t; } public async Task GetWechatToKen() { var Provider = _externalAuthConfiguration.Providers.FirstOrDefault(P => P.Name == ProviderName); var appid = Provider.ClientId; var secret = Provider.ClientSecret; try { var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); httpClient.Timeout = TimeSpan.FromMinutes(3); var urlToken = $"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={appid}&corpsecret={secret}"; string ResultToken = await httpClient.GetStringAsync(urlToken); WeChatToken wX_Token = JsonConvert.DeserializeObject(ResultToken); return wX_Token; } catch (Exception ex) { throw new UserFriendlyException("获取微信access_token失败" + ex.Message); } } public async Task GetWechatUserId(string code,string token) { try { var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); httpClient.Timeout = TimeSpan.FromMinutes(3); var urlGetUserInfo = $"https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={token}&code={code}"; var ResultUserInfo = await httpClient.GetStringAsync(urlGetUserInfo); WeChatUserInfo wXUserInfo = JsonConvert.DeserializeObject(ResultUserInfo); return wXUserInfo; } catch (Exception ex) { throw new UserFriendlyException("获取微信UserInfo失败" + ex.Message);
       }
     }
  }
}

 

3.修改配置文件 appsetttings.json

 

 

3. ABP .NETCore 添加企业微信第三方登录_第2张图片

 

 

 

 

 "EnterpriseWechat": {
      "IsEnabled": "true",
      "AppId": "",
      "Secret": ""
 }

4.注入第三方登录 在WebCoreModule.cs 中添加注入代码

  public override void PreInitialize()
  {
    ConfigureExternalAuthProviders();
  }



public void ConfigureExternalAuthProviders() { IocManager.Register(); IocManager.Register(); var externalAuthConfiguration = IocManager.Resolve(); if (bool.Parse(_appConfiguration["Authentication:EnterpriseWechat:IsEnabled"])) { externalAuthConfiguration.Providers.Add( new ExternalLoginProviderInfo( WechatMiniProgramAuthProviderApi.ProviderName, _appConfiguration["Authentication:EnterpriseWechat:AppId"], _appConfiguration["Authentication:EnterpriseWechat:Secret"], typeof(WechatMiniProgramAuthProviderApi) ) ); } }

 

5.接下来最后一步就是修改  ExternalAuthenticate 方法,因为里面的代码ABP默认就已经我们实现了一些东西,需要根据自己实际的需要进行修改。

3. ABP .NETCore 添加企业微信第三方登录_第3张图片

 

 

 

 

发布下项目测试下自动登录吧。

 

你可能感兴趣的:(3. ABP .NETCore 添加企业微信第三方登录)