Asp.Net Core 企業(yè)微信靜默授權(quán)的實(shí)現(xiàn)
企業(yè)微信接口文檔
1. 構(gòu)造授權(quán)網(wǎng)頁(yè)鏈接

2.回調(diào)獲取到 Code 通過(guò)code+access_token去 請(qǐng)求用戶(hù)信息


調(diào)試準(zhǔn)備工作 -->內(nèi)網(wǎng)穿透+域名 推薦向日葵有免費(fèi)的,免費(fèi)的開(kāi)發(fā)測(cè)試夠用了
域名的配置成可信用

上代碼 Demo下載
[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>
/// 授權(quán)地址
/// </summary>
private readonly string _auth2url = "https://open.weixin.qq.com/connect/oauth2/authorize";
/// <summary>
/// 授權(quán)回調(diào)地址
/// </summary>
private readonly string _callbackurl = "http://******.zicp.vip/auth2callback/api/Auth2/Callback";
/// <summary>
/// 獲取access_token地址
/// </summary>
private readonly string _gettokenurl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
/// <summary>
/// 獲取訪問(wèn)用戶(hù)身份地址
/// </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只能消費(fèi)一次,不能重復(fù)消費(fèi)。比如說(shuō),是否存在多個(gè)服務(wù)器同時(shí)消費(fèi)同一code情況。
2)code需要在有效期間消費(fèi)(5分鐘),過(guò)期會(huì)自動(dòng)失效。
*/
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)
{
//企業(yè)成員
string UserId = userinfo.UserId;
//外部成員
string OpenId = userinfo.OpenId;
/**
userid是系統(tǒng)生成的可以修改一次;
所以后面的業(yè)務(wù)邏輯如果遇到錯(cuò)誤就要重新授權(quán)一下;
*/
if (UserId==null)
{
_memoryCache.Set<string>("UserId", OpenId);
}
else
{
_memoryCache.Set<string>("UserId", UserId);
}
}
else
{
_logger.LogError($"getuserinfo請(qǐng)求錯(cuò)誤:{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
{
_logger.LogError($"access_token請(qǐng)求錯(cuò)誤:{access_token_result.errmsg }");
}
}
}
}
return _memoryCache.Get<string>("AccessToken");
}
}
到此這篇關(guān)于Asp.Net Core 企業(yè)微信靜默授權(quán)的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Asp.Net Core 靜默授權(quán)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Asp.net MVC 中利用jquery datatables 實(shí)現(xiàn)數(shù)據(jù)分頁(yè)顯示功能
這篇文章主要介紹了Asp.net MVC 中利用jquery datatables 實(shí)現(xiàn)數(shù)據(jù)分頁(yè)顯示功能,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-06-06
asp.net core調(diào)用wps實(shí)現(xiàn)word轉(zhuǎn)pdf的過(guò)程
這篇文章主要介紹了asp.net core調(diào)用wps實(shí)現(xiàn)word轉(zhuǎn)pdf的過(guò)程,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2024-08-08
asp.net core下給網(wǎng)站做安全設(shè)置的方法詳解
這篇文章主要給大家介紹了關(guān)于asp.net core下給網(wǎng)站做安全設(shè)置的相關(guān)資料,文章通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-07-07
ASP.NET MVC5使用MiniProfiler監(jiān)控MVC性能
這篇文章主要為大家詳細(xì)介紹了ASP.NET MVC5使用MiniProfiler監(jiān)控MVC性能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07
.NET Core創(chuàng)建一個(gè)控制臺(tái)(Console)程序
這篇文章主要為大家詳細(xì)介紹了.NET Core如何創(chuàng)建一個(gè)控制臺(tái)程序,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-04-04
.NET Core類(lèi)庫(kù)System.Reflection.DispatchProxy實(shí)現(xiàn)簡(jiǎn)易Aop的方法
這篇文章主要給大家介紹了關(guān)于.NET Core類(lèi)庫(kù)System.Reflection.DispatchProxy實(shí)現(xiàn)簡(jiǎn)易Aop的相關(guān)資料,文中通過(guò)示例代碼結(jié)束的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-12-12
Entity?Framework?Core基于數(shù)據(jù)模型創(chuàng)建數(shù)據(jù)庫(kù)
這篇文章介紹了Entity?Framework?Core基于數(shù)據(jù)模型創(chuàng)建數(shù)據(jù)庫(kù)的方法,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04

