外部登录不使用身份asp.net核心2.0

Luk*_*eva 2 authentication asp.net-mvc asp.net-core-2.0

我正在尝试为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);
}
Run Code Online (Sandbox Code Playgroud)

这很好用,它将我重定向到google,facebook或linkedinn身份验证.

现在就这一部分:

public async Task<IActionResult> ExternalLoginCallback()
{
    //Extract info from externa; login

    return Redirect("/");
}
Run Code Online (Sandbox Code Playgroud)

我想要的只是获取外部登录提供的信息.

我尝试过从研究中发现的东西,

 var result = await HttpContext.AuthenticateAsync(provider);
 if (result?.Succeeded != true)
 {
     return Redirect("/");
 }
 var externalUser = result.Principal;
 var claims = externalUser.Claims.ToList();
Run Code Online (Sandbox Code Playgroud)

首先,我不确定?provider=Google我的回调字符串上的简单字符是否会传递我指定的提供程序名称,因此可以用它来检查登录方案.我想这是不正确的.其次,我尝试了硬编码await HttpContext.AuthenticateAsync("Google"),当它到达此代码时,调试停止.我不知道为什么.

我在使用单一身份验证创建项目时看到了生成的代码.

var info = await _signInManager.GetExternalLoginInfoAsync();
Run Code Online (Sandbox Code Playgroud)

遗憾的是,我将无法使用身份,因为我没有用户存储,而且我的应用程序将使用API​​.

Ref*_*eft 6

首先,您需要创建自定义cookie处理程序.我自己也有问题:

没有IAuthenticationSignInHandler配置为处理该方案的登录:承载

我必须添加一个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";
});
Run Code Online (Sandbox Code Playgroud)

这里的重要部分是"YourCustomScheme".

现在是时候从回调操作中的外部身份验证提供的声明中检索用户信息了.

调节器

[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;
}
Run Code Online (Sandbox Code Playgroud)

瞧!我们现在有一些用户信息可供使用!

在此输入图像描述

有用的链接

http://docs.identityserver.io/en/release/topics/signin_external_providers.html