ASP.NET-ADFS身份验证挂钩

时间:2019-05-24 06:15:16

标签: asp.net-web-api wif adfs3.0

我有一个针对ADFS服务器进行身份验证的ASP.NET Web API。身份验证启动类的定义如下:

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数据库中创建用户记录已经。

在完成上述任务后,是否有某种方法可以直接截取响应?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。 WsFederationAuthenticationOptions类具有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);

}