最快的方式是直接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); } }