2017-05-04 88 views
0

我有很多应用程序,我将身份验证切换到ADFS,我需要添加自定义数据,让登录成功后可以说数据库中的角色数组。添加自定义数据到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服务器上的控制器和API和我的ADFS 2012

我owin启动这样

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

多小时后,我解决了这个问题 在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); 
       } 
      }, 

     });