Asp.Net Implementation of wechat silent authorization for core enterprises

Time:2021-1-6

Enterprise wechat interface document

1. Construct authorized web links

2. Call back to get the code through code + access_ Token goRequest user information

3. Get access_ token

Debugging preparation work — > intranet penetration + domain name recommendation sunflower is free, free development test is enough

The configuration of domain name is creditable

Upper codeDemo download

[ApiController]
  [Route("api/[controller]")]
  public class Auth2Controller : ControllerBase
  {

    private readonly string _agentId = "1000002";
    private readonly string _secret = "Y3f8ESBIBJoC8M_FPHOlpvmghS_Nn2ceFePRVZjw9_E";
    private readonly string _corpId = "wwbf72a7a059eac0f8";
    /// <summary>
    ///Authorized address
    /// </summary>
    private readonly string _auth2url = "https://open.weixin.qq.com/connect/oauth2/authorize";
    /// <summary>
    ///Authorization callback address
    /// </summary>
    private readonly string _callbackurl = "http://******.zicp.vip/auth2callback/api/Auth2/Callback";
    /// <summary>
    ///Get access_ Token address
    /// </summary>
    private readonly string _gettokenurl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
    /// <summary>
    ///Get access user identity address
    /// </summary>
    private readonly string _getuserurl = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo";


    private readonly ILogger<Auth2Controller> _logger;
    private readonly IHttpClientFactory _clientFactory;
    private readonly IMemoryCache _memoryCache;

    public Auth2Controller(ILogger<Auth2Controller> logger, IHttpClientFactory clientFactory, IMemoryCache memoryCache)
    {
      _logger = logger;
      _clientFactory = clientFactory;
      _memoryCache = memoryCache;
    }   

    [HttpGet]
    public IActionResult Auth2(string redirecturi)
    {
      string strurl = $"{_auth2url}?" +
          $"&appid={_corpId}" +
          $"&redirect_uri={System.Web.HttpUtility.UrlEncode(_callbackurl)}" +
          $"&response_type=code" +
          $"&scope={_secret}" +
          $"&agentid={_agentId}" +
          $"&state={System.Web.HttpUtility.UrlEncode(redirecturi)}#wechat_redirect";
      return Redirect(strurl);
    }

    [HttpGet("Callback")]
    public async Task<IActionResult> Callback(string code, string state)
    {
      /**
       1) Code can only be consumed once, not repeatedly. For example, is there a case where multiple servers consume the same code at the same time.
       2) The code needs to be consumed within the validity period (5 minutes), and the expiration will be invalid automatically.
       */      
      string access_token = await GetAccessToken();
      string url = $"{_getuserurl}?access_token={access_token}&code=[code]";
      HttpResponseMessage response = await _clientFactory.CreateClient().GetAsync(url);
      if (response.StatusCode == System.Net.HttpStatusCode.OK)
      {
        using (var responseStream = await response.Content.ReadAsStreamAsync())
        {
          var userinfo = JsonConvert.DeserializeObject<dynamic>(new StreamReader(responseStream).ReadToEnd());
          int errcode = userinfo.errcode;
          if (errcode == 0)
          {
            //Enterprise members
            string UserId = userinfo.UserId;
            //External members
            string OpenId = userinfo.OpenId;
            /**
             The userid is generated by the system and can be modified once;
             Therefore, if the following business logic encounters errors, it is necessary to re authorize it;   
             */
            if (UserId==null)
            {
              _memoryCache.Set<string>("UserId", OpenId);
            }
            else
            {
              _memoryCache.Set<string>("UserId", UserId);
            }
          }
          else
          {
            A kind of logger.LogError ($"getUserInfo request error:{ userinfo.errmsg }");
            return Ok();
          }
        }
      }      
      return Redirect($"{System.Web.HttpUtility.UrlDecode(state)}?UserId={_memoryCache.Get<string>("UserId")}");
    }
    public async Task<string> GetAccessToken()
    {
      if (_memoryCache.Get<string>("AccessToken") == null)
      {
        string url = $"{_gettokenurl}?corpid={_corpId}&corpsecret={_secret}";
        HttpResponseMessage response = await _clientFactory.CreateClient().GetAsync(url);
        if (response.StatusCode == System.Net.HttpStatusCode.OK)
        {
          using (var responseStream = await response.Content.ReadAsStreamAsync())
          {
            var access_token_result = JsonConvert.DeserializeObject<dynamic>(new StreamReader(responseStream).ReadToEnd());
            int errcode = access_token_result.errcode;
            if (errcode == 0)
            {
              string access_token = access_token_result.access_token;
              int expires_in = access_token_result.expires_in;
              _memoryCache.Set<string>("AccessToken", access_token, DateTimeOffset.Now.AddSeconds(expires_in - 10));
            }
            else
            {
              A kind of logger.LogError ($"access_ Token request error: {access}_ token_ result.errmsg  }");
            }
          }

        }
      }
      return _memoryCache.Get<string>("AccessToken");
    }
  }

This is about Asp.Net This is the article about the implementation of wechat silent authorization for core enterprises, and more about it Asp.Net Core Silent authorization content, please search previous articles of developer or continue to browse the following related articles. I hope you can support developer more in the future!