将xml请求中的用户名和密码传递给wcf服务进行身份验证?

问题描述:

我有一个wcf服务,用户在进行服务调用之前需要进行身份验证。不会有用户通过登录验证的网站,或者用户验证的Windows /控制台应用程序。我想这样做是这样的:将xml请求中的用户名和密码传递给wcf服务进行身份验证?

传入一个请求:

<GetCars> 
    <Credentials username="test" password="test" /> 
</GetCars> 

如果用户名和密码是成功的,返回GetCars否则无法成功响应。

问题是我不知道如何将请求传递给上述的wcf服务,然后读取用户名和密码属性来验证它。

+0

您可能还想研究内置对WCF SOAP请求进行身份验证处理的WS-Security。 – mellamokb 2011-05-12 19:51:08

+0

我正在使用wsHttpBinding。我不清楚发送XML请求时代码的放置位置。 – Xaisoft 2011-05-12 19:51:48

我将很快尝试描述我在我自己的WCF服务中使用的身份验证方法。使用WS-Security规范(即,您正在使用wsHttpBinding)的WCF SOAP端点具有内置的身份验证处理。您可以实现在web.config中使用的设置是这样的:

<bindings> 
    <wsHttpBinding> 
    <binding name="myBindingName"> 
     <security mode="Message"> 
     <transport clientCredentialType="None" /> 
     <message clientCredentialType="UserName" /> 
     </security> 

然后,你可以指定一个自定义类型来处理身份验证逻辑:

<behaviors> 
    <serviceBehaviors> 
    <behavior name="myBehaviorName"> 
     <serviceCredentials> 
     <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="NameSpaceName.Class,AssemblyName" /> 
     </serviceCredentials> 

这个类来处理身份验证逻辑应该延伸UserNamePasswordValidator(需要引用System.IdentityModel.dll并导入System.IdentityModel.Selectors此),并覆盖Validate

public class MyValidator : UserNamePasswordValidator { 
    public override void Validate(string userName, string password) { 
     // check password. if success, do nothing 
     // if fail, throw a FaultException 
    } 
} 

调用使用一个ASP.Net WCF客户端需要使用ClientCredential通过用户名和密码,这样的代码:

// This pattern needs to be repeated and username/password set with every creation 
// of a client object. This can be refactored to a separate method to simplify. 
MyAPIClient client = new MyAPIClient(); 

// yes UserName is there twice on purpose, that's the proper structure 
client.ClientCredentials.UserName.UserName = theUsername; 
client.ClientCredentials.UserName.Password = thePassword; 

try { 
    client.Open(); 
    client.DoSomething(); 
    client.Close(); 
} catch (Exception ex) { 
    // handle exception, which should contain a FaultException; 
    // could be failed login, or problem in DoSomething 
} 

显然,结合和上述定义的行为已经被分配到使用behaviorConfiguration服务本身和bindingConfiguration属性。

+0

我已经拥有了您在web.config中提到的所有内容,并且我有一个自定义验证器,那么您是否在说我的验证应该读取用户名并来自xml文件的密码并将其设置为ClientCredentials的用户名和密码 – Xaisoft 2011-05-12 20:02:09

+0

此认证结构正在取代您从XML请求中解析它的想法。 “验证”应该包含您在语句背后的逻辑“如果用户名和密码成功,返回GetCars的成功响应否则失败。”什么是确定用户名和密码是否成功?这就是'验证'应该做的。 – mellamokb 2011-05-12 20:04:25

+0

在我的情况下,用户名和密码将来自xml请求。我想我可以使用Linq到Xml读取用户名和密码属性? – Xaisoft 2011-05-12 20:16:50