Asp.net core 学习笔记之 authen + autho + oidc + oauth + spa 第九篇 (external login)

External login 就是指通过 Google, Microsoft, Facebook account 做登入.

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/?view=aspnetcore-5.0&tabs=visual-studio

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/microsoft-logins?view=aspnetcore-5.0 (Microsoft)

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/google-logins?view=aspnetcore-5.0 (Google)

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/facebook-logins?view=aspnetcore-5.0 (Facebook)

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/other-logins?view=aspnetcore-5.0 (其它)

但是没有 Apple 

Microsoft account

services.AddAuthentication().AddMicrosoftAccount(options =>
{
    options.ClientId = "client id";
    options.ClientSecret = "client secret";
    options.SaveTokens = true;
    options.Scope.Add("https://graph.microsoft.com/User.ReadBasic.All");
    options.Scope.Add("https://graph.microsoft.com/Calendars.ReadWrite");
    options.Scope.Add("https://graph.microsoft.com/Mail.ReadWrite");
    options.Scope.Add("offline_access");
});

也可以获取到 mail 和 calendar 等等的权限, offline_access 就是要求 refresh token 咯.

所有 permission scope 在这里 : https://docs.microsoft.com/en-us/graph/permissions-reference#calendars-permissions

下面是关于 sign in 的流程, 可以去 identity scaffold template 看

这样可以获取到所有注册的 providers

var externalLoginProviders = (await signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

redirect 用户到 third party 授权页面

public IActionResult OnPostExternalLogin([FromForm] ExternalLoginDto dto)
{
    var properties = _signInManager.ConfigureExternalAuthenticationProperties(dto.Provider, "/account/login"); // callback url
    return new ChallengeResult(dto.Provider, properties);
}

获取 profile 和 token infomation

var info = await _signInManager.GetExternalLoginInfoAsync();

里面基本上什么都有, name, email, access token, refresh token. 然后就可以做很多事情了 

测试的时候经常需要 clear 授权, Microsoft account 是在这里 clear https://account.live.com/consent/Manage?mkt=en-US

Google Account

怎样去 google cloud 申请 app client

https://developers.google.com/identity/sign-in/web/sign-in

google 规定挺多的, 如果是 internal use 需要 google workspace 如果是 public 用需要 verify company.

不然就只可以 set 几个 test user 去玩玩. 

然后它不可以通过 local ip 来测试. 一定要发布到网站. redirect url 一定要是真的域名. 域名也需要 verify.

等下次我认证搞的时候才 test 弄呗.

Facebook Account

照着做就可以了 facebook 可以 local test 只是 privacy policy page 必须放一个 online 的 url (要可以访问的)

测试时可以到这里移除 facebook 的授权

request permission 不是用 scope 的方式, 而是通过在 client app 里面 setting, 而且需要很多同意. 感觉 facebook 对这块可能比较严格. 

原文地址:https://www.cnblogs.com/keatkeat/p/14961511.html