ASP.NET - ADFS 身份验证挂钩

ASP.NET - ADFS authentication hook

我有一个 ASP.NET 网络 API 可以针对 ADFS 服务器进行身份验证。身份验证启动 class 定义如下:

public void ConfigureAuth(IAppBuilder app)

{

    app.UseCookieAuthentication(
        new CookieAuthenticationOptions
        {
        AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType
        });

    app.UseWsFederationAuthentication(
        new WsFederationAuthenticationOptions
        {
            MetadataAddress = ConfigurationManager.AppSettings["ADFSMetadata"],
            Wtrealm = ConfigurationManager.AppSettings["Wtrealm"]
        });


    app.SetDefaultSignInAsAuthenticationType(WsFederationAuthenticationDefaults.AuthenticationType);

}

我想要的是,当用户通过 ADFS 成功验证并返回令牌时,如果在 ADFS 返回的声明中找到电子邮件,则应在我的 SQL 数据库中创建一条用户记录数据库中不存在。

有没有办法在认证后直接拦截响应来完成上述任务?

我找到了解决办法。 WsFederationAuthenticationOptions class 有一个 Notification 属性 可用于挂钩身份验证成功和失败响应。

例如

public void ConfigureAuth(IAppBuilder app)

{

    app.UseCookieAuthentication(
        new CookieAuthenticationOptions
        {
        AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType
        });

    app.UseWsFederationAuthentication(
        new WsFederationAuthenticationOptions
        {
            MetadataAddress = ConfigurationManager.AppSettings["ADFSMetadata"],
            Wtrealm = ConfigurationManager.AppSettings["Wtrealm"],
            Notifications = new WsFederationAuthenticationNotifications
            {
                AuthenticationFailed = context =>
                {
                    context.HandleResponse();
                    context.Response.Redirect("/Error?message=" + context.Exception.Message);
                    return Task.FromResult(0);
                },
                SecurityTokenReceived = context =>
                {
                    // Get the token
                    var token = context.ProtocolMessage.GetToken();                    
                    return Task.FromResult(0);
                }
            }
        });


    app.SetDefaultSignInAsAuthenticationType(WsFederationAuthenticationDefaults.AuthenticationType);

}