2011-05-23 42 views
1

我在Message下的安全模式下使用clientCredentailType作爲用戶名。我創建了一個自定義用戶名和密碼驗證程序類來驗證用戶名和密碼。如何在WCF中獲取自定義用戶名/密碼

我想使用這些憑據(用戶名,密碼)授權給服務中的不同操作。我想知道什麼是存儲用戶名和密碼以便重複使用的最佳方式。我應該使用我的自定義驗證器類將它們存儲在靜態變量中,以便它們可以到處訪問嗎?

爲什麼我不能使用System.Threading.Thread.CurrentPrincipal.Identity.Name,我試圖獲取用戶名,但它不顯示任何內容,我如何獲取密碼?

感謝 阿德南

回答

0

線程的CurrentPrincipal屬性是Windows身份服務下運行。您的服務正在以用戶名/密碼的形式接收客戶端身份,並且與服務身份無關。 WCF支持impersonation and delegation,但不使用您的服務正在使用的自定義身份驗證方案。

對此question的接受答案可能是您正在尋找的。如果這不起作用,那麼在代碼中手動執行此操作會非常快。

+0

我能夠通過此代碼獲取用戶名 – adnangohar 2011-05-24 12:06:56

+0

OperationContext oc = OperationContext.Current; ServiceSecurityContext ssc = oc.ServiceSecurityContext; string client = ssc.PrimaryIdentity.Name; 有什麼方法可以獲得密碼嗎? – adnangohar 2011-05-24 12:07:27

+0

簡短的回答是沒有。安全上下文將爲授權用戶提供「身份」,通常由用戶/帳戶名稱以及用戶所屬的角色/羣組組成。由於密碼僅用於身份驗證,因此它絕不會暴露給已經通過身份驗證的用戶。基本上,唯一可用的時間是在認證過程中。允許任何進程在認證過程之外訪問密碼是非常不安全的。 – 2011-05-24 15:11:51

1

只處理和使用您的自定義驗證器中的憑據。如果憑證有效,則使用自定義授權策略爲該用戶準備一組具有角色的自定義主體,並使用PrincipalPermission屬性修飾您的服務方法。

[PrincipalPermission(SecurityAction.Demand, Authenticated = true, Role = "ClearedForUsingFoo")] 
public void Foo(string bar) 
{ 
... 


class AuthorizationPolicy : IAuthorizationPolicy 
{ 
    public bool Evaluate(EvaluationContext evaluationContext, ref object state) 
    { 
     // get the authenticated client identity 
     IIdentity identity = GetClientIdentity(evaluationContext); 

     // set the custom principal 
     evaluationContext.Properties["Principal"] = new CustomPrincipal(identity); 

     return true; 
    } 

    public ClaimSet Issuer 
    { 
     get { throw new NotImplementedException(); } 
    } 

    public string Id 
    { 
     get { return "FooBarApp.AuthorizationPolicy"; } 
    } 

    private static IIdentity GetClientIdentity(EvaluationContext evaluationContext) 
    { 
     object obj; 
     if (!evaluationContext.Properties.TryGetValue("Identities", out obj)) 
      throw new Exception("No Identity found"); 

     IList<IIdentity> identities = obj as IList<IIdentity>; 
     if (identities == null || identities.Count <= 0) 
      throw new Exception("No Identity found"); 

     return identities[0]; 
    } 
} 
+0

謝謝奧利弗。我是身份框架的新手,我剛剛通過了一些文檔。我有點困惑,如果我有我自己的自定義數據庫與用戶和角色,身份框架如何幫助我。我如何映射我的自定義用戶/角色與WIF,以便我可以將它們用作其他內置角色功能,即(Windows帳戶,ASPNET角色等)。如果您有任何關於此的文章,請讓我知道。 – adnangohar 2011-05-24 12:06:01

相關問題