2017-05-04 37 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); 
       } 
      }, 

     });