我正在为Intranet应用程序编写WCF服务器。我是WCF的新手并且对身份验证有一些疑问。对于此服务器,绑定将为netTcp,建议使用netTcpBinding和Windows身份验证。但是对于我的要求,我需要一个自定义登录,其中用户将使用自己的凭据而不是Windows凭证进行验证 我打算以这种方式实现服务合同并验证登录凭据
*[ServiceContract(SessionMode = SessionMode.Required)]
public interface Iservice
{
[OperationContract]
String Login(String username, String password);
}
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession) ]
public class serviceclass : Iservice
{
String Login(String username, String password);
{
//Validate uname and password with DB.
if (validate)
return OperationContext.Current.SessionId;
else return String.Empty;
}
}*
Is this a good approach or is there a better approach to acheive this.
请指导。
答案 0 :(得分:0)
我建议您使用UserNamePasswordValidator进行自定义验证,它符合您的要求。
您只需要继承并实现UserNamePasswordValidator类的验证,如下所示:
public class CustomUserNameValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
if (null == userName || null == password)
{
throw new ArgumentNullException();
}
if (!(userName == "test1" && password == "1tset") && !(userName == "test2" && password == "2tset"))
{
// This throws an informative fault to the client.
throw new FaultException("Unknown Username or Incorrect Password");
// When you do not want to throw an infomative fault to the client,
// throw the following exception.
// throw new SecurityTokenException("Unknown Username or Incorrect Password");
}
}
}
您可以替换静态用户名和密码,并在数据存储中验证它。
服务配置:
<serviceBehaviors>
<behavior name="CustomValidator">
<serviceCredentials>
<userNameAuthentication
userNamePasswordValidationMode="Custom"
customUserNamePasswordValidatorType=
"MyAssembly.CustomUserNameValidator, MyAssembly"/>
</serviceCredentials>
</behavior>
<serviceBehaviors>
<netTcpBinding>
<binding name="tcpWithMessageSecurity">
<security mode="Message" >
<message clientCredentialType="UserName"/>
</security>
</binding>
</netTcpBinding>
对于客户端,您可以使用凭据填充用户名和密码。
proxy.ClientCredentials.UserName.UserName = "user";
proxy.ClientCredentials.UserName.Passsord = "password";