企业微信接口文档
1. 构造授权网页链接
2.回调获取到 Code 通过code+access_token去 请求用户信息
3. 获取access_token
调试准备工作 -->内网穿透+域名 推荐向日葵有免费的,免费的开发测试够用了
域名的配置成可信用
上代码 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>
/// 授权地址
/// </summary>
private readonly string _auth2url = "https://open.weixin.qq.com/connect/oauth2/authorize";
/// <summary>
/// 授权回调地址
/// </summary>
private readonly string _callbackurl = "http:/
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)
{
//企业成员
string UserId = userinfo.UserId;
//外部成员
string OpenId = userinfo.OpenId;
if (UserId==null)
{
_memoryCache.Set<string>("UserId", OpenId);
}
else
{
_memoryCache.Set<string>("UserId", UserId);
}
}
else
{
_logger.LogError($"getuserinfo请求错误:{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请求错误:{access_token_result.errmsg }");
}
}
}
}
return _memoryCache.Get<string>("AccessToken");
}
}
到此这篇关于Asp.Net Core 企业微信静默授权的实现的文章就介绍到这了,更多相关Asp.Net Core 静默授权内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
您可能感兴趣的文章:ASP.NET Core学习之使用JWT认证授权详解浅谈ASP.NET Core 中jwt授权认证的流程原理asp.net core 授权详解asp.net core2.2多用户验证与授权示例详解