简体   繁体   中英

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

But without using configuration files. Can anyone show me how?

Edit: I want to implement both AuthorizationPolicy and the CustomValidator.

Are you referring about how to add the AuthorizationPolicy through code? 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 :

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:

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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