如何在ASP.NET Core 2.0 MVC应用程序的HomeController中获取当前的外部提供程序 [英] How to get the current external provider in HomeController of ASP.NET Core 2.0 MVC application

查看:132
本文介绍了如何在ASP.NET Core 2.0 MVC应用程序的HomeController中获取当前的外部提供程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用单个帐户创建ASP.NET Core 2.0 MVC. Google和Microsoft身份验证工作正常.现在,我正在使用它来访问Google和Microsoft帐户中的数据(这种情况发生在HomeController中).如果我知道要使用哪个提供程序,我就可以做到这一点.

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.

在AccountController中,可立即使用有关当前使用的提供商(例如Google,Microsoft)的信息.

In AccountController, the info about the currently used provider (e.g. Google, Microsoft) is available out-of-the-box.

但是此信息不会持续存在,因此我无法在HomeController中使用它.从HomeController访问时,signInManager.GetExternalLoginInfoAsync()返回null.

But this info does not persist so I can't use it in HomeController. signInManager.GetExternalLoginInfoAsync() returns null when accessed from HomeController.

我可以自己(通过更改AccountController.ExternalLoginCallback)将其保存到一些持久性存储中,但是可能存在冗余,因为有正确/推荐的方法可以通过其他方式获取当前提供程序?或使signInManager.GetExternalLoginInfoAsync在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.

注意:关于"signInManager.GetExternalLoginInfoAsync为null"的讨论有很多问题,但是它们涉及的另一种情况是,即使在AccountController中也为null(通常是由于外部提供程序的配置错误).我的情况不同,signInManager.GetExternalLoginInfoAsync在这里工作正常.

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.

推荐答案

使用外部提供程序登录时,SignInManager将类型为http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod的声明添加到ClaimsPrincipal(

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.

下面是一些示例代码,您应该可以直接将它们插入HomeController:

Here's some example code that you should be able to plug in to your HomeController as is:

var externalProvider = User.FindFirstValue(ClaimTypes.AuthenticationMethod);

这篇关于如何在ASP.NET Core 2.0 MVC应用程序的HomeController中获取当前的外部提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆