asp.net核心身份验证中的signin-google如何与Google处理程序链接?

oll*_*leo 3 authentication asp.net-core

我进入了源代码,但看不到它连接到处理程序的位置。在GoogleExtensions.cs文件中,我看到了

 => builder.AddOAuth<GoogleOptions, GoogleHandler>(authenticationScheme,
                                                   displayName, configureOptions);
Run Code Online (Sandbox Code Playgroud)

但是我不明白路由“ / signin-google”如何调用处理程序。

itm*_*nus 5

asp.net核心身份验证中的signin-google如何与Google处理程序链接?

这个问题可以分为两个小问题。

  1. 用户如何重定向到的网址 /signin-google
  2. 如何GoogleHandler处理请求/signin-google

用户如何重定向到 signin-google

最初,当用户单击Google按钮以使用Google身份验证登录时,浏览器将向以下网址发布请求:

https://your-server/Identity/Account/ExternalLogin?returnUrl=%2F
Run Code Online (Sandbox Code Playgroud)

您的服务器只需将用户重定向到Google.com,并要求Google验证当前用户:

https://accounts.google.com/o/oauth2/v2/auth?
    response_type=code
    &client_id=xxx
    &scope=openid%20profile%20email
    &redirect_uri=https%3A%2F%2Fyour-server%2Fsignin-google
    &state=xxx
Run Code Online (Sandbox Code Playgroud)

当谷歌已经成功地验证用户,它将用户到你的网站重定向使用的参数,code根据redirect_uri上面。

 https://your-server/signin-google?
    state=xxx
    &code=yyy
    &scope=zzz
    &authuser=0
    &session_state=abc
    &prompt=none
Run Code Online (Sandbox Code Playgroud)

请注意,此处的路径等于/signin-google 这是第一个关键点。

如何GoogleHandler处理signin-google

我们谈论如何之前GoogleHandler所说,我们应该看看如何AuthenticationMiddlewareAuthenticationHanlder工作:

  1. 当有传入请求时,AuthenticationMiddleware(将UseAuthentication()在您的Configure()方法中通过进行注册Startup.cs)将检查每个请求并尝试对用户进行身份验证。

  2. 由于您已将身份验证服务配置为使用google身份验证,因此AuthenticationMiddleware将会调用GoogleHandler.HandleRequestAsync()方法

  3. 如果需要,GoogleHandler.HandleRequestAsync()使用OAuth2.0协议处理远程身份验证,并获取用户的身份。

在此GoogleHandler继承自RemoteAuthenticationHandler<TOptions>,及其HandleRequestAsync()方法将用于AuthenticationMiddleware确定是否需要处理请求。。返回true时,表示当前请求已由身份验证处理程序处理,并且将不再执行任何处理。

那么,如何HandleRequestAsync()确定请求是否应由自己处理呢?

HandleRequestAsync()方法只是对照来检查当前路径Options.CallbackPath。参见下面的源代码:

public abstract class RemoteAuthenticationHandler<TOptions> : AuthenticationHandler<TOptions>, IAuthenticationRequestHandler
    where TOptions : RemoteAuthenticationOptions, new()
{
   // ...

   public virtual Task<bool> ShouldHandleRequestAsync()
        => Task.FromResult(Options.CallbackPath == Request.Path);

    public virtual async Task<bool> HandleRequestAsync()
    {
        if (!await ShouldHandleRequestAsync())
        {
            return false;
        }
        // ... handle remote authentication , such as exchange code from google
    }
}
Run Code Online (Sandbox Code Playgroud)

闭幕

整个工作流程将是:

  1. 用户单击按钮以登录Google
  2. Google对用户进行身份验证并将其重定向到 /signin-google
  3. 由于path == signin-google,因此中间件将用于HandleRequestAsync()处理当前请求,并与google交换代码。
  4. ...做其他事情