我想做与此链接相同的事情:
http://www.codeproject.com/KB/WCF/Custom_Authorization_WCF.aspx
但不使用配置文件。谁能告诉我怎么样?
编辑:我想实现AuthorizationPolicy和CustomValidator。
答案 0 :(得分:9)
您是指如何通过代码添加AuthorizationPolicy?未经测试,但我相信这样的事情应该有效:
ServiceHost host = ...;
var col = new ReadOnlyCollection<IAuthorizationPolicy>(new IAuthorizationPolicy[] { new MyPolicy() });
ServiceAuthorizationBehavior sa = host.Description.Behaviors.Find<ServiceAuthorizationBehavior>();
if ( sa == null ) {
sa = new ServiceAuthorizationBehavior();
host.Description.Behaviors.Add(sa);
}
sa.ExternalAuthorizationPolicies = col;
答案 1 :(得分:0)
如果您参考this topic (WCF Security: Getting the password of the user) by Rory Primrose,他会提供类似于您提供自定义验证器的信息,重要的扩展方法为CreateSecurityTokenManager
:
public class PasswordServiceCredentials : ServiceCredentials
{
public PasswordServiceCredentials()
{
}
private PasswordServiceCredentials(PasswordServiceCredentials clone)
: base(clone)
{
}
protected override ServiceCredentials CloneCore()
{
return new PasswordServiceCredentials(this);
}
public override SecurityTokenManager CreateSecurityTokenManager()
{
// Check if the current validation mode is for custom username password validation
if (UserNameAuthentication.UserNamePasswordValidationMode == UserNamePasswordValidationMode.Custom)
{
return new PasswordSecurityTokenManager(this);
}
Trace.TraceWarning(Resources.CustomUserNamePasswordValidationNotEnabled);
return base.CreateSecurityTokenManager();
}
}
要使用此自定义服务凭据,您需要在配置中的<ServiceCredentials>
ConfigurationElement
上指定type属性,例如:
<serviceCredentials type="your.assembly.namespace.PasswordServiceCredentials,
your.assembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" >
</serviceCredentials>
同样,您可以以编程方式设置此type
属性,但我不熟悉如何。