最快的方式是直接nuget安装AspNetCore.Authentication.WeChat包。
想要知道是如何实现的,可以看下面github上面的源码。
源码在这里:https://github.com/china-live/QQConnect
使用方式:
- 安装nuget的包以后,在startup.cs中添加微信授权认证并配置appId和AppSecret,使用缓存保存State数据(微信State Too Long 报错 由于微信的设置,state最多128字节,但是默认生成的state会超出限制,所以需要加入缓存)
iservices.AddAuthentication().AddWeChat(options => { options.AppId = Configuration["WeixinSetting:WeixinAppId"]; options.AppSecret = Configuration["WeixinSetting:WeixinAppSecret"]; options.UseCachedStateDataFormat = true; });
- 新建一个Controller,编写action
/// <summary> /// 微信授权登录 /// </summary> /// <param name="returnUrl">用户尝试进入的需要登录的页面</param> /// <returns></returns> [AllowAnonymous] public ActionResult WxLogin(string returnUrl) { string redirectUrl = Url.Action("BaseCallback", new { ReturnUrl = returnUrl }); var properties = signInManager .ConfigureExternalAuthenticationProperties("WeChat", redirectUrl); return new ChallengeResult("WeChat", properties); } /// <summary> /// 回调 /// </summary> /// <param name="provider"></param> /// <param name="returnUrl">用户最初尝试进入的页面</param> /// <returns></returns> [AllowAnonymous] public async Task<IActionResult> BaseCallback(string provider = null, string returnUrl = "/") { try { ExternalLoginInfo info = await signInManager.GetExternalLoginInfoAsync(); if (info == null) { return RedirectToAction(nameof(Login)); } var result = await signInManager.ExternalLoginSignInAsync( info.LoginProvider, info.ProviderKey, false); if (result.Succeeded) { return Redirect(returnUrl); } else { Account user = new Account { OpenId = info.Principal.FindFirst(ClaimTypes.NameIdentifier).Value, UserName = info.Principal.FindFirst(ClaimTypes.NameIdentifier).Value }; IdentityResult identResult = await userManager.CreateAsync(user); if (identResult.Succeeded) { identResult = await userManager.AddLoginAsync(user, info); if (identResult.Succeeded) { await signInManager.SignInAsync(user, false); return Redirect(returnUrl); } } return AccessDenied(); } } catch (Exception ex) { return Content("发生错误:" + ex); } }