Programmatically specify user authorization for WCF (NetTcpBinding)

I want to do the same as in this link:

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

But without the use of configuration files. Can someone show me how?

Edit: I want to implement both AuthorizationPolicy and CustomValidator.

+6
c # authorization wcf
source share
2 answers

Do you mean how to add an authorization code through a code? Unverified, 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; 
+8
source share

If you refer to this section (WCF Security: Obtaining a User Password) by Rory Primrose , it does the same as asking for a custom validator, an important extension method is 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 these custom service credentials, you need to specify the type attribute in the <ServiceCredentials> ConfigurationElement in your configuration, for example:

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

Similarly, you can set this type attribute programmatically, but I don't know how to do it.

0
source share

All Articles