我正在尝试在不使用身份框架的情况下为 facebook、google 和linkedin 创建一个外部登录方案。我有一个存储所有用户并执行一些身份验证的 api。现在我对如何从外部登录获取信息有点迷茫。
我正在发出这样的挑战。
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider)
{
//Issue a challenge to external login middleware to trigger sign in process
return new ChallengeResult(provider);
}
这很有效,它将我重定向到 google、facebook 或linkedinn 身份验证。
现在在这部分:
public async Task<IActionResult> ExternalLoginCallback()
{
//Extract info from externa; login
return Redirect("/");
}
我想要的只是获取外部登录提供的信息。
我已经尝试了我从研究中发现的东西,
var result = await HttpContext.AuthenticateAsync(provider);
if (result?.Succeeded != true)
{
return Redirect("/");
}
var externalUser = result.Principal;
var claims = externalUser.Claims.ToList();
首先,我不确定是否是一个简单的
?provider=Google
在我的回调字符串上将传递我指定的提供程序名称,以便它可以用于检查登录方案。我想这是不正确的。其次,我尝试了硬编码 await HttpContext.AuthenticateAsync("Google")
当它到达此代码时,调试停止。我不知道为什么。我在创建具有单一身份验证的项目时看到了生成的代码。
var info = await _signInManager.GetExternalLoginInfoAsync();
遗憾的是,我将无法使用身份,因为我没有用户存储并且我的应用程序将使用 API。
最佳答案
首先,您需要创建一个自定义 cookie 处理程序。我自己有以下问题:
No IAuthenticationSignInHandler is configured to handle sign in for the scheme: Bearer
我不得不添加一个 cookie 处理程序来临时存储外部身份验证的结果,例如由外部提供商发送的声明。这是必要的,因为在您完成外部身份验证过程之前,通常会涉及几个重定向。
创业
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
{
o.TokenValidationParameters = tokenValidationParameters;
})
.AddCookie("YourCustomScheme")
.AddGoogle(googleOptions =>
{
googleOptions.SignInScheme = "YourCustomScheme";
googleOptions.ClientId = "x";//Configuration["Authentication:Google:ClientId"];
googleOptions.ClientSecret = "x";//Configuration["Authentication:Google:ClientSecret"];
//googleOptions.CallbackPath = "/api/authentication/externalauthentication/signin-google";
});
这里的重要部分是“YourCustomScheme”。
现在是时候从回调操作中外部身份验证提供的声明中检索用户信息了。
Controller
[AllowAnonymous]
[HttpPost(nameof(ExternalLogin))]
public IActionResult ExternalLogin(ExternalLoginModel model)
{
if (model == null || !ModelState.IsValid)
{
return null;
}
var properties = new AuthenticationProperties { RedirectUri = _authenticationAppSettings.External.RedirectUri };
return Challenge(properties, model.Provider);
}
[AllowAnonymous]
[HttpGet(nameof(ExternalLoginCallback))]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
//Here we can retrieve the claims
var result = await HttpContext.AuthenticateAsync("YourCustomScheme");
return null;
}
瞧!我们现在有一些用户信息可以使用!
有用的链接
http://docs.identityserver.io/en/release/topics/signin_external_providers.html
关于asp.net-mvc - 不使用身份的外部登录 asp.net core 2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46753437/