问题
I'm creating ASP.NET Core 2.0 MVC with individual accounts. Google and Microsoft authentication is working fine. Now I'm using it to access data in Google and Microsoft accounts (this happens in HomeController). I can do this just fine if I know which provider to use.
In AccountController, the info about the currently used provider (e.g. Google, Microsoft) is available out-of-the-box.
But this info does not persist so I can't use it in HomeController. signInManager.GetExternalLoginInfoAsync()
returns null when accessed from HomeController.
I can save this into some persistent storage myself (by altering AccountController.ExternalLoginCallback
) but probably this would be redundant as there is a correct/recommended way to get the current provider by other means? Or to make signInManager.GetExternalLoginInfoAsync
work in HomeController.
Note: there are many questions discussing "signInManager.GetExternalLoginInfoAsync is null" but they are about another case when it's null even in AccountController (usually due to incorrect configuration of an external provider). My case is different and signInManager.GetExternalLoginInfoAsync
is working fine there.
回答1:
When signing in using an external provider, SignInManager
adds a claim of type http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod
to the ClaimsPrincipal
(source). You can read this value to determine which provider was used for sign-in.
Here's some example code that you should be able to plug in to your HomeController
as is:
var externalProvider = User.FindFirstValue(ClaimTypes.AuthenticationMethod);
来源:https://stackoverflow.com/questions/56478047/how-to-get-the-current-external-provider-in-homecontroller-of-asp-net-core-2-0-m