add扩展方法
public static class JwtConfiguration { public static void AddJwtConfiguration(this IServiceCollection services, IConfiguration configuration) { services.AddAuthentication(opts => { opts.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; }).AddCookie(options => { options.LoginPath = "/signin"; options.LogoutPath = "/signout"; }).AddGitHub(options => { options.ClientId = configuration["Authentication:GitHub:ClientId"]; options.ClientSecret = configuration["Authentication:GitHub:ClientSecret"]; }); } }startup.cs
ConfigureServices中配置此服务
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddJwtConfiguration(Configuration);创建AuthenticationController.cs
增加SignIn
在signin方法中,用户点击授权后(第一次),会根据其传递的URL,重定向到这个地址,signin-callback,参数也会一同携带。provider为GitHub,redirectUrl为::8081/login-result.
[HttpGet("~/signin-callback")] public async Task<IActionResult> Home(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 || string.IsNullOrWhiteSpace(openIdClaim.Value)) return Redirect(redirectUrl); //TODO 记录授权成功后的信息 string email = authenticateResult.Principal.FindFirst(ClaimTypes.Email)?.Value; string name = authenticateResult.Principal.FindFirst(ClaimTypes.Name)?.Value; string gitHubName = authenticateResult.Principal.FindFirst(GitHubAuthenticationConstants.Claims.Name)?.Value; string gitHubUrl = authenticateResult.Principal.FindFirst(GitHubAuthenticationConstants.Claims.Url)?.Value; //startup 中 AddGitHub配置项 options.ClaimActions.MapJsonKey(LinConsts.Claims.AvatarUrl, "avatar_url"); string avatarUrl = authenticateResult.Principal.FindFirst(LinConsts.Claims.AvatarUrl)?.Value; return Redirect($"{redirectUrl}?openId={openIdClaim.Value}"); } 参考.net Core2.2 WebApi通过OAuth2.0实现微信登录
AspNetCore3.0 和 JWT
用户系统设计:第三方授权、账号绑定及解绑(下)
Demo 示例GitHub https://github.com/luoyunchong/dotnetcore-examples/tree/master/dotnetcore3.1/VoVo.AspNetCore.OAuth2