作者:五蘊非空
連結:http://www.cnblogs.com/rsls/p/10522649.html
前言
微信相關配置請參考微信公眾平臺(https://mp.weixin.qq.com/wiki?t=resource/res_main&id;=mp1421140842) 的這篇文章。
註意授權回呼域名一定要修改正確。
微信網頁授權是透過OAuth2.0機制實現的,所以我們可以使用 https://github.com/china-live/QQConnect 這個開源專案提供的中介軟體來實現微信第三方登入的流程。
開發流程
1、新建一個.NET Core WebAPI專案。
在NuGet中查詢並安裝 AspNetCore.Authentication.WeChat 包。
2、修改 appsettings.json 配置檔案,增加以下配置:
"Authentication": {
"WeChat": {
"AppId": "微信AppID",
"AppSecret": "微信AppSecret"
}
},
"Logging": {
"LogLevel": {
"Default": "Debug", //日誌級別從低到高,依次為:Debug,Information,Warning,Error,None
"Microsoft.EntityFrameworkCore": "Error",
"System": "Error"
}
}
3、修改 Startup
services.AddSingleton();
services.AddAuthentication()
.AddWeChat(wechatOptions =>
{
wechatOptions.AppId = Configuration["Authentication:WeChat:AppId"];
wechatOptions.AppSecret = Configuration["Authentication:WeChat:AppSecret"];
wechatOptions.UseCachedStateDataFormat = true;
});
4、新增 AccountController
[Route("api/[controller]")]
[ApiController]
public class AccountController : ControllerBase
{
private const string LoginProviderKey = "LoginProvider";
private const string Provider_WeChat = "WeChat";
private readonly ILogger _logger;
private readonly IHttpContextAccessor _contextAccessor;
public AccountController(ILogger logger,
IHttpContextAccessor contextAccessor)
{
_logger = logger;
_contextAccessor = contextAccessor;
}
///
/// 微信登入
///
/// 授權成功後的跳轉地址
///
[ ]
public IActionResult LoginByWeChat(string redirectUrl)
{
var request = _contextAccessor.HttpContext.Request;
var url = $”{request.Scheme}://{request.Host}{request.PathBase}{request.Path}Callback?provider={Provider_WeChat}&redirectUrl;={redirectUrl}“;
var properties = new AuthenticationProperties { RedirectUri = url };
properties.Items[LoginProviderKey] = Provider_WeChat;
return Challenge(properties, Provider_WeChat);
}
///
/// 微信授權成功後自動回呼的地址
///
///
/// 授權成功後的跳轉地址
///
[ ]
public async Task LoginByWeChatCallbackAsync(string provider = null, string redirectUrl = “”)
{
var authenticateResult = await _contextAccessor.HttpContext.AuthenticateAsync(provider);
if (!authenticateResult.Succeeded) return Redirect(redirectUrl);
var openIdClaim = authenticateResult.Principal.FindFirst(ClaimTypes.NameIdentifier);
if (openIdClaim == null || openIdClaim.Value.IsNullOrWhiteSpace())
return Redirect(redirectUrl);
//TODO 記錄授權成功後的微信資訊
var city = authenticateResult.Principal.FindFirst(“urn:wechat:city”)?.Value;
var country = authenticateResult.Principal.FindFirst(ClaimTypes.Country)?.Value;
var headimgurl = authenticateResult.Principal.FindFirst(ClaimTypes.Uri)?.Value;
var nickName = authenticateResult.Principal.FindFirst(ClaimTypes.Name)?.Value;
var openId = authenticateResult.Principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var privilege = authenticateResult.Principal.FindFirst(“urn:wechat:privilege”)?.Value;
var province = authenticateResult.Principal.FindFirst(“urn:wechat:province”)?.Value;
var sexClaim = authenticateResult.Principal.FindFirst(ClaimTypes.Gender);
int sex = 0;
if (sexClaim != null && !sexClaim.Value.IsNullOrWhiteSpace())
sex = int.Parse(sexClaim.Value);
var unionId = authenticateResult.Principal.FindFirst(“urn:wechat:unionid”)?.Value;
_logger.LogDebug($”WeChat Info=> openId: {openId},nickName: {nickName}“);
return Redirect($”{redirectUrl}?openId={openIdClaim.Value}“);
}
}
5、將網站釋出到外網,請求https://你的授權域名/api/account/LoginByWeChat?redirectUrl=授權成功後要跳轉的頁面
即可調起微信授權頁面。
註意
-
微信授權必須使用https
-
微信開放平臺和微信公眾平臺都有提供網站用微信登入的介面,前者適用於任何網站,後者只適用於微信服務號的內嵌網站
相關原始碼地址:https://github.com/ren8179/QrF.OAuth.WeChat/tree/master