Foreword
Micro-channel configuration, see micro-channel public platform of this article. Note authorize callback domain name must be correctly modified.
Micro-letter web authorization is achieved through OAuth2.0 mechanism, so we can use https://github.com/china-live/QQConnect middleware open source project to implement micro-channel third-party login process.
Development Process
1, a new .net core webapi project. Find and install NuGet in the AspNetCore.Authentication.WeChat
package.
2, modify appsettings.json
the configuration file, add the following configuration:
1 "Authentication": { 2 "WeChat": { 3 "AppId": "微信AppID", 4 "AppSecret": "微信AppSecret" 5 } 6 }, 7 "Logging": { 8 "LogLevel": { 9 "Default": "Debug", //The logging level from low to high, followed by: the Debug, Information, Warning, Error, None 10 " Microsoft.EntityFrameworkCore " : " Error " , . 11 " the System " : " Error " 12 is } 13 is }
3. Modify Startup
1 services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); 2 services.AddAuthentication() 3 .AddWeChat(wechatOptions => 4 { 5 wechatOptions.AppId = Configuration["Authentication:WeChat:AppId"]; 6 wechatOptions.AppSecret = Configuration["Authentication:WeChat:AppSecret"]; 7 wechatOptions.UseCachedStateDataFormat = true; 8 });
4, new AccountController
1 [Route("api/[controller]")] 2 [ApiController] 3 public class AccountController : ControllerBase 4 { 5 private const string LoginProviderKey = "LoginProvider"; 6 private const string Provider_WeChat = "WeChat"; 7 private readonly ILogger _logger; 8 private readonly IHttpContextAccessor _contextAccessor; 9 10 public the AccountController (ILogger <the AccountController> Logger, . 11 IHttpContextAccessor contextAccessor) 12 is { 13 is _logger = Logger; 14 _contextAccessor = contextAccessor; 15 } 16 /// <Summary> . 17 /// WeChat log 18 is /// </ Summary> . 19 / // <param name = "the redirectUrl"> after the authorization is successful jump address </ param> 20 is /// <Returns> </ Returns> 21 is [HttpGet ( " LoginByWeChat ")] 22 public IActionResult LoginByWeChat(string redirectUrl) 23 { 24 var request = _contextAccessor.HttpContext.Request; 25 var url = $"{request.Scheme}://{request.Host}{request.PathBase}{request.Path}Callback?provider={Provider_WeChat}&redirectUrl={redirectUrl}"; 26 var properties = new AuthenticationProperties { RedirectUri = url }; 27 properties.Items[LoginProviderKey] = Provider_WeChat; 28 returnChallenge (Properties, Provider_WeChat); 29 } 30 /// <Summary> 31 is /// automatic callback address of the micro-channel authorization succeeds 32 /// </ Summary> 33 is /// <param name = "Provider"> </ param> 34 is /// <param name = "the redirectUrl"> jump address after successful authorization </ param> 35 /// <Returns> </ Returns> 36 [HttpGet ( " LoginByWeChatCallback " )] 37 [ public the async the Task < IActionResult> LoginByWeChatCallbackAsync ( String Provider = null ,string redirectUrl = "") 38 { 39 var authenticateResult = await _contextAccessor.HttpContext.AuthenticateAsync(provider); 40 if (!authenticateResult.Succeeded) return Redirect(redirectUrl); 41 var openIdClaim = authenticateResult.Principal.FindFirst(ClaimTypes.NameIdentifier); 42 if (openIdClaim == null || openIdClaim.Value.IsNullOrWhiteSpace()) 43 return Redirect(redirectUrl); 44 //TODO 记录授权成功后的微信信息 45 var city = authenticateResult.Principal.FindFirst("urn:wechat:city")?.Value; 46 var country = authenticateResult.Principal.FindFirst(ClaimTypes.Country)?.Value; 47 var headimgurl = authenticateResult.Principal.FindFirst(ClaimTypes.Uri)?.Value; 48 var nickName = authenticateResult.Principal.FindFirst(ClaimTypes.Name)?.Value; 49 var openId = authenticateResult.Principal.FindFirst(ClaimTypes.NameIdentifier)?.Value; 50 var privilege = authenticateResult.Principal.FindFirst("urn:wechat:privilege")?.Value; 51 var province = authenticateResult.Principal.FindFirst("urn:wechat:province")?.Value; 52 var sexClaim = authenticateResult.Principal.FindFirst(ClaimTypes.Gender); 53 int sex = 0; 54 if (sexClaim != null && !sexClaim.Value.IsNullOrWhiteSpace()) 55 sex = int.Parse(sexClaim.Value); 56 var unionId = authenticateResult.Principal.FindFirst("urn:wechat:unionid")?.Value; 57 _logger.LogDebug($"WeChat Info=> openId: {openId},nickName: {nickName}"); 58 return Redirect($"{redirectUrl}?openId={openIdClaim.Value}"); 59 } 60 }
5, will be posted to the site outside the network, request
1 HTTPS: // ? After your authoritative name / api / account / LoginByWeChat redirectUrl = authorization succeeded to jump pages
To bring up from the micro-channel authorization page.
note
Micro-channel authorization must use https
WeChat open platform and has a micro-channel public platform website that provides an interface with a micro-channel logged in, the former suitable for any website, which only applies to micro-channel service number's embedded website
Benpian related Source Address: https://github.com/ren8179/QrF.OAuth.WeChat/tree/master