How to set a Security Token in WCF?

Paul Fryer picture Paul Fryer · Nov 8, 2010 · Viewed 8.4k times · Source

I'm upgrading an application from .net 1.1 to 3.5. This app connects to a WCF service. Previously the web service client was configured to use a Security Token, like so:

RegistrationWSWse registrationService = new RegistrationWSWse();
Microsoft.Web.Services2.Security.Tokens.UsernameToken token = new Microsoft.Web.Services2.Security.Tokens.UsernameToken("some username", "some password", Microsoft.Web.Services2.Security.Tokens.PasswordOption.SendPlainText );
registrationService.RequestSoapContext.Security.MustUnderstand=false;
registrationService.RequestSoapContext.Security.Tokens.Add(token);

Now I have added a new service reference in Visual Studio to the web service, but the auto generated code doesn't provide any way to set the security header, like above.

Is this something that needs to be configured in the config file, system.serviceModel section?


Update

The reason I didn't see the username/password properties was because I was working with the service interface, not the actual implementation class.

I was able to set these things by casting the instance to the type, like this:

((RegistrationWSClient)registrationWs).ChannelFactory.Credentials.UserName.UserName = userName;
((RegistrationWSClient)registrationWs).ChannelFactory.Credentials.UserName.Password = password;

The other important thing you have to do is update your client app.config file. If you don't do this the username/password won't be set int he SOAP header. Example:

<security mode="TransportWithMessageCredential" />

Answer

Kamyar picture Kamyar · Nov 8, 2010

Check out this article on MSDN. This post also has some good information about your question.