.net Core2.2 WebApi通过OAuth2.0实现微信登录
程序员文章站
2022-07-11 09:39:25
前言 微信相关配置请参考 微信公众平台 的这篇文章。注意授权回调域名一定要修改正确。 微信网页授权是通过OAuth2.0机制实现的,所以我们可以使用 https://github.com/china-live/QQConnect 这个开源项目提供的中间件来实现微信第三方登录的流程。 开发流程 1、新 ......
前言
微信相关配置请参考 的这篇文章。注意授权回调域名一定要修改正确。
微信网页授权是通过oauth2.0机制实现的,所以我们可以使用 https://github.com/china-live/qqconnect 这个开源项目提供的中间件来实现微信第三方登录的流程。
开发流程
1、新建一个.net core webapi 项目。在nuget中查找并安装 aspnetcore.authentication.wechat
包。
2、修改 appsettings.json
配置文件,增加以下配置:
1 "authentication": { 2 "wechat": { 3 "appid": "微信appid", 4 "appsecret": "微信appsecret" 5 } 6 }, 7 "logging": { 8 "loglevel": { 9 "default": "debug", //日志级别从低到高,依次为:debug,information,warning,error,none 10 "microsoft.entityframeworkcore": "error", 11 "system": "error" 12 } 13 }
3、修改 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、新增 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 accountcontroller(ilogger<accountcontroller> logger, 11 ihttpcontextaccessor contextaccessor) 12 { 13 _logger = logger; 14 _contextaccessor = contextaccessor; 15 } 16 /// <summary> 17 /// 微信登录 18 /// </summary> 19 /// <param name="redirecturl">授权成功后的跳转地址</param> 20 /// <returns></returns> 21 [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 return challenge(properties, provider_wechat); 29 } 30 /// <summary> 31 /// 微信授权成功后自动回调的地址 32 /// </summary> 33 /// <param name="provider"></param> 34 /// <param name="redirecturl">授权成功后的跳转地址</param> 35 /// <returns></returns> 36 [httpget("loginbywechatcallback")] 37 public async 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、将网站发布到外网,请求
https://你的授权域名/api/account/loginbywechat?redirecturl=授权成功后要跳转的页面
即可调起微信授权页面。
注意
微信授权必须使用https
微信开放平台和微信公众平台都有提供网站用微信登录的接口,前者适用于任何网站,后者只适用于微信服务号的内嵌网站
本篇相关源码地址:https://github.com/ren8179/qrf.oauth.wechat/tree/master