簡體   English   中英

如何在WCF調用的服務端獲取用戶名和密碼?

[英]How to get the Username and Password in the service side of a WCF call?

當我使用以下代碼在客戶端提供憑據時:

myChannelFactory.Credentials.UserName.UserName = "username";
myChannelFactory.Credentials.UserName.Password = "password";

然后在服務器端,我看到這些憑據可用

operationContext.IncomingMessageHeaders[1]

但是有沒有更方便的方法來獲取UserName和密碼? 我在OperationContext看到的只是屬性和無類型列表的混亂,我無法找到任何指示我可以得到它的地方。

您可以使用ServiceSecurityContext上的靜態Current屬性來獲取正在調用的操作的當前ServiceSecurityContext

然后,您可以使用PrimaryIdentity屬性以獲取傳入憑據的用戶的標識。

但是,它不會(也不應該)公開密碼。 如果您確實需要密碼,那么您必須下拉到消息級別並檢查標題,如您所見。

這完全取決於您使用的綁定,並且沒有一般答案。

例如,如果您使用NetNamedPipeBinding並執行此操作

myChannelFactory.Credentials.UserName.UserName = "username";
myChannelFactory.Credentials.UserName.Password = "password"; 

你浪費時間:客戶端綁定對這些數據不起作用,它不會出現在消息中,並且在服務端根本無法訪問。

如果綁定配置了指定使用用戶名/密碼憑據的安全選項,則綁定將僅使用此數據。 執行此操作的所有標准綁定將使用憑據進行身份驗證,其結果將通過ServiceSecurityContext顯示在ServiceSecurityContext如casperOne所示,並且不包括密碼數據。

為了支持身份驗證,數據必須攜帶在郵件頭中的某個位置。 究竟在哪里以及以何種形式再次依賴於約束力。 不要以為你總是會在operationContext.IncomingMessageHeaders[1]找到它們。

編輯:您可以構建一個自定義綁定,為您提供所需的內容。

CustomBinding binding = new CustomBinding( ... );
binding.Elements.Insert(1, 
  SecurityBindingElement.CreateUserNameOverTransportBindingElement());

在服務端,提供UserNamePasswordValidator並配置如下憑據:

serviceHost.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = 
  System.ServiceModel.Security.UserNamePasswordValidationMode.Custom;
servicehost.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = 
  new MyUserNamePasswordValidator();

然后,用戶名和密碼將傳遞給MyUserNamePasswordValidatorValidate方法。

警告:除非您使用安全傳輸,否則這不是安全的身份驗證機制,因為憑據在郵件頭中以明文形式發送。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM