简体   繁体   English

以编程方式为WCF指定自定义授权(NetTcpBinding)

[英]Programmatically specify custom authorization for WCF (NetTcpBinding)

I want to do the same thing as in this link: 我想做与此链接相同的事情:

http://www.codeproject.com/KB/WCF/Custom_Authorization_WCF.aspx http://www.codeproject.com/KB/WCF/Custom_Authorization_WCF.aspx

But without using configuration files. 但是不使用配置文件。 Can anyone show me how? 谁能告诉我怎么样?

Edit: I want to implement both AuthorizationPolicy and the CustomValidator. 编辑:我想实现AuthorizationPolicy和CustomValidator。

Are you referring about how to add the AuthorizationPolicy through code? 您是指如何通过代码添加AuthorizationPolicy? Untested, but I believe something like this should work: 未经测试,但我相信这样的事情应该有效:

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;

If you refer to the this topic (WCF Security: Getting the password of the user) by Rory Primrose , he achieves similar to what you're enquiring about with providing a custom validator, the important extension method being CreateSecurityTokenManager : 如果你参考Rory Primrose这个主题(WCF安全:获取用户的密码) ,他会提供类似于你提供自定义验证器的信息,重要的扩展方法是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();
    }
}

To use this custom service credential, you will need to specify the type attribute on the <ServiceCredentials> 's ConfigurationElement in your configuration, like: 要使用此自定义服务凭据,您需要在ConfigurationElement中的<ServiceCredentials>ConfigurationElement上指定type属性,例如:

<serviceCredentials type="your.assembly.namespace.PasswordServiceCredentials, 
     your.assembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" >
</serviceCredentials>

Likewise, you could set this type attribute programatically, but I'm not familiar with how. 同样,您可以以编程方式设置此type属性,但我不熟悉如何。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM