在ASP.NET中,AuthenticationManager.GetExternalLoginInfoAsync方法返回外部登录信息。如果该方法始终返回空值,可能是由于以下几个常见问题导致的:
Startup.cs文件的ConfigureAuth方法中正确配置了外部登录提供程序。例如,如果你使用的是Google登录,应该添加以下代码:app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
ClientId = "your_client_id",
ClientSecret = "your_client_secret"
});
回调URL不正确:确保在外部登录提供程序的开发者控制台中设置了正确的回调URL。回调URL应该与你的应用程序的URL匹配,并且应该在URL末尾添加一个特定的路径,例如/signin-google。
请求令牌被阻止:如果你的应用程序在防火墙或代理服务器后面运行,并且阻止了外部请求令牌,则可能会导致GetExternalLoginInfoAsync始终返回空值。确保你的服务器可以访问外部登录提供程序的令牌URL。
以下是一个完整的示例,演示如何正确地配置和使用AuthenticationManager.GetExternalLoginInfoAsync方法:
Startup.cs:
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
// 配置应用程序的身份验证和授权
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
// 配置外部登录
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// 添加Google登录
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
ClientId = "your_client_id",
ClientSecret = "your_client_secret"
});
}
}
AccountController.cs:
public class AccountController : Controller
{
private ApplicationUserManager _userManager;
private ApplicationSignInManager _signInManager;
public AccountController()
{
}
public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
{
UserManager = userManager;
SignInManager = signInManager;
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager();
}
private set
{
_userManager = value;
}
}
public ApplicationSignInManager SignInManager
{
get
{
return _signInManager ?? HttpContext.GetOwinContext().Get();
}
private set
{
_signInManager = value;
}
}
// 处理外部登录回调
[AllowAnonymous]
public async Task ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
// 处理无效的登录信息
return RedirectToAction("Login");
}
// 根据外部登录信息执行用户登录或注册逻辑
var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
case SignInStatus.Failure:
default:
// 如果用户没有帐户,提示他们创建一个帐户
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
}
}
// 辅助方法
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
}
在上述示例中,ExternalLoginCallback方法使用AuthenticationManager.GetExternalLoginInfoAsync来获取外部登录信息。如果loginInfo为空,会重定向到登录页面或其他适当的操作。否则,根据外部登录信息执行相应的用户登录或注册逻辑。
希望以上解