将自定义数据添加到ADFS authintication

时间:2017-05-04 10:18:46

标签: c# asp.net ws-federation adfs3.0

我有很多应用程序,我正在将身份验证切换到ADFS,我需要添加自定义数据,然后在登录成功后从数据库中说出角色数组。

场景解释: 每个应用程序都有自己的角色数据库 在用户进行身份验证并请求授权Application_AuthenticateRequest(object sender, EventArgs e)之后,我将可以添加角色作为此类声明

 ((ClaimsIdentity)((ClaimsPrincipal)currentUser).Identity)
                    .AddClaim(new Claim(ClaimTypes.Role, "role1FromDataBase"));
                HttpContext.Current.User = currentUser;

但是每个请求都会调用Application_AuthenticateRequest方法,我不希望每次都从db请求角色。 所以我需要在某处添加这些角色,以便我可以调用它们。当然,当我处理基于API角色的授权时,Sessions和Cookies不是最佳实践。

应用程序在Windows Server 2012上有控制器和API以及我的Adfs

我的Owin Startup就像这样

app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

    app.UseCookieAuthentication(new CookieAuthenticationOptions());
    app.UseWsFederationAuthentication(
        new WsFederationAuthenticationOptions
        {
            Wtrealm = realm,
            MetadataAddress = adfsMetadata,

            Notifications = new WsFederationAuthenticationNotifications()
            {

                RedirectToIdentityProvider = context =>
                {   

                    context.ProtocolMessage.Wreply = "https://localhost:44329/";
                    return Task.FromResult(0);
                }
            },

        });


    app.UseStageMarker(PipelineStage.Authenticate);

所以我该怎么办?

1 个答案:

答案 0 :(得分:2)

几个小时后我解决了这个问题 在Startup类和public void Configuration(IAppBuilder app)方法中 我们必须将带有角色的声明添加到WsFederationAuthenticationOptions 像这样

 app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions
        {
            Wtrealm = realm,
            MetadataAddress = adfsMetadata,

            Notifications = new WsFederationAuthenticationNotifications()
            {
                // this method will be invoked after login succes 
                SecurityTokenValidated = notification =>
                {
                    ClaimsIdentity identity = notification.AuthenticationTicket.Identity;
                    // here we can add claims and specify the type, in my case i want to add Role Claim
                    identity.AddClaim(new Claim(ClaimTypes.Role, "student"));

                    return Task.FromResult(0);
                },
                RedirectToIdentityProvider = context =>
                {

                    context.ProtocolMessage.Wreply = "https://localhost:44329/";
                    return Task.FromResult(0);
                }
            },

        });