Loading

IdentityServer Topics(5)- 使用第三方登录

ASP.NET Core 有一个灵活的方式来处理外部认证,有如下几个步骤:

如果你使用了 ASP.NET Identity,ASP.NET Identity 对于许多底层代码都做了封装, 建议阅读Microsoft文档并查看ASP.NET Identity快速入门源码,以此来充分了解 ASP.NET Identity。

一.添加外部认证处理程序

与外部认证提供者交互所需的协议实现被封装在一个认证处理程序中。 一些提供者使用专有协议(例如Facebook等社交提供者),一些使用标准协议, OpenID Connect,WS-Federation或SAML2p。

请参阅此快速入门以了解添加外部认证并对其进行配置的分步说明。

二.cookies的作用

外部认证处理程序上的一个设置 SignInScheme,例如:

services.AddAuthentication()
    .AddGoogle("Google", options =>
    {
        options.SignInScheme = "scheme of cookie handler to use";

        options.ClientId = "...";
        options.ClientSecret = "...";
    })

登录 scheme 指定将暂时存储外部认证的结果的cookie处理程序的名称,例如 由外部提供商发送的身份信息单元(Claim)。 这是必要的,因为在完成外部认证过程之前,通常会有几个重定向(比如QQ登录的跳转)。

鉴于这是一种常见的做法,IdentityServer 专门为此外部提供程序工作流程注册一个Cookie处理程序。 该方案通过IdentityServerConstants.ExternalCookieAuthenticationScheme常量表示。 如果你要使用 IdentityServer 提供外部cookie处理程序,那么对于上面的SignInScheme,默认值为IdentityServerConstants.ExternalCookieAuthenticationScheme常量:

services.AddAuthentication()
    .AddGoogle("Google", options =>
    {
        options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;

        options.ClientId = "...";
        options.ClientSecret = "...";
    })

您也可以注册您自己的自定义Cookie处理程序,如下所示:

services.AddAuthentication()
    .AddCookie("YourCustomScheme")
    .AddGoogle("Google", options =>
    {
        options.SignInScheme = "YourCustomScheme";

        options.ClientId = "...";
        options.ClientSecret = "...";
    })

对于特定的场景,你可以不使用外部Cookie机制,将外部用户直接转发到主要Cookie处理程序。 这通常涉及在外部处理程序上处理事件,以确保从外部身份源执行正确的身份信息(Claim)转换。

三. 触发认证

你可以通过HttpContext上的ChallengeAsync扩展方法(或使用MVC ChallengeResult)调用外部认证处理程序。

如果传递某些设置,比如: returnUrl和scheme可以这样设置:

var callbackUrl = Url.Action("ExternalLoginCallback");

var props = new AuthenticationProperties
{
    RedirectUri = callbackUrl,
    Items =
    {
        { "scheme", provider },
        { "returnUrl", returnUrl }
    }
};

return Challenge(provider, props);

四. 回调处理程序和用户签名

在回调页面上,通常任务是:

  • 检查由外部提供商返回的身份。
  • 如果处理用户,对于已存在的用户和新用户的处理是不同的
  • 新用户在登入可能需要额外的步骤和UI界面。
  • 可能会创建一个内部账户来绑定外部身份
  • 存储你要保留的外部身份信息单元(Claim)。
  • 删除临时cookie
  • 登录用户

** 检查外部身份:**

// read external identity from the temporary cookie
var result = await HttpContext.AuthenticateAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);
if (result?.Succeeded != true)
{
    throw new Exception("External authentication error");
}

// retrieve claims of the external user
var externalUser = result.Principal;
if (externalUser == null)
{
    throw new Exception("External authentication error");
}

// retrieve claims of the external user
var claims = externalUser.Claims.ToList();

// try to determine the unique id of the external user - the most common claim type for that are the sub claim and the NameIdentifier
// depending on the external provider, some other claim type might be used
var userIdClaim = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject);
if (userIdClaim == null)
{
    userIdClaim = claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);
}
if (userIdClaim == null)
{
    throw new Exception("Unknown userid");
}

var externalUserId = userIdClaim.Value;
var externalProvider = userIdClaim.Issuer;

// use externalProvider and externalUserId to find your user, or provision a new user

** 清理和登录:**

// issue authentication cookie for user
await HttpContext.SignInAsync(user.SubjectId, user.Username, provider, props, additionalClaims.ToArray());

// delete temporary cookie used during external authentication
await HttpContext.SignOutAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);

// validate return URL and redirect back to authorization endpoint or a local page
if (_interaction.IsValidReturnUrl(returnUrl) || Url.IsLocalUrl(returnUrl))
{
    return Redirect(returnUrl);
}

return Redirect("~/");

五.State,URL Length和ISecureDataFormat

当重定向到外部登录时,来自客户端应用程序的状态必须频繁进行往返。 这意味着状态在离开客户端之前被捕获并保存直到用户返回到客户端应用程序。 许多协议(包括OpenID Connect)都允许将某种状态作为参数传递,身份提供者将在响应中返回该状态。 ASP.NET Core提供的OpenID Connect身份验证处理程序利用了该协议的这一功能,这就是它如何实现上述的returnUrl功能。

在请求参数中存储状态的问题是请求URL可能会变得太大(超过2000个字符的公共限制)。 OpenID Connect身份验证处理程序的确提供了一个可扩展点,用于将状态存储在服务器中,而不是在请求URL中。 您可以通过实现ISecureDataFormat 并在OpenIdConnectOptions上配置它来实现这一点。

幸运的是,IdentityServer为您提供了一个实现,由在DI容器中注册的IDistributedCache实现(例如,独立的MemoryDistributedCache)支持。 要使用IdentityServer提供的安全数据格式实现,只需在配置DI时在IServiceCollection上调用AddOidcStateDataFormatterCache扩展方法即可。 如果没有参数传递,则所有配置的OpenID Connect处理程序将使用IdentityServer提供的安全数据格式实现:

public void ConfigureServices(IServiceCollection services)
{
    // configures the OpenIdConnect handlers to persist the state parameter into the server-side IDistributedCache.
    services.AddOidcStateDataFormatterCache();

    services.AddAuthentication()
        .AddOpenIdConnect("demoidsrv", "IdentityServer", options =>
        {
            // ...
        })
        .AddOpenIdConnect("aad", "Azure AD", options =>
        {
            // ...
        })
        .AddOpenIdConnect("adfs", "ADFS", options =>
        {
            // ...
        });
}

如果只配置特定方案,则将这些方案作为参数传递:

public void ConfigureServices(IServiceCollection services)
{
    // configures the OpenIdConnect handlers to persist the state parameter into the server-side IDistributedCache.
    services.AddOidcStateDataFormatterCache("aad", "demoidsrv");

    services.AddAuthentication()
        .AddOpenIdConnect("demoidsrv", "IdentityServer", options =>
        {
            // ...
        })
        .AddOpenIdConnect("aad", "Azure AD", options =>
        {
            // ...
        })
        .AddOpenIdConnect("adfs", "ADFS", options =>
        {
            // ...
        });
}
posted @ 2017-12-29 16:34  晓晨Master  阅读(6056)  评论(1编辑  收藏  举报