Validating Username, password and timestamp in WCF
Recently I have got an requirement which is to validate username, password and timestamp set in the message header in each call made to WCF.
Following is the solution I came Up with.
Validating Username and Password
Step 1:
Create a wshttpbinding and add the following configuration.
- <wsHttpBinding>
- <binding name="wsHttpBinding" closeTimeout="00:00:10" openTimeout="00:00:10" receiveTimeout="00:00:10" sendTimeout="00:00:10">
- <security mode="Message">
- <message clientCredentialType="UserName" />
- </security>
- </binding>
- </wsHttpBinding>
Step 2:
Create a custom username and password validator as below
- public class UserValidator : UserNamePasswordValidator
- {
- public override void Validate(string userName, string password)
- {
- if (null == userName || null == password)
- {
- throw new ArgumentNullException();
- }
- // your validation logic comes under here
- if(!ValidateUser(userName,password))
- throw new FaultException("Invalid username or password");
- }
- }
Step 3
Add the following configuration section.
- <behaviors>
- <serviceBehaviors>
- <behavior name="ServiceBehavior">
- <serviceMetadata httpGetEnabled="true" />
- <serviceDebug includeExceptionDetailInFaults="false" />
- <serviceCredentials>
- <serviceCertificate findValue="0789B7C8F0018E869EA9DB95B208BFB0C3449A3D"
- x509FindType="FindByThumbprint" />
- <userNameAuthentication userNamePasswordValidationMode="Custom"
- customUserNamePasswordValidatorType="WcfService.MobilityIntegrationService.UserValidator, WcfService.MobilityIntegrationService" />
- </serviceCredentials>
- </behavior>
- </serviceBehaviors>
- </behaviors>
Validating Timestamp
- public class TimeStampValidator
- {
- public void ValidateTimeStamp()
- {
- string ns = HybridConfig.GetAppSetting("MessageNamespace");
- int timespanExpiry =-Convert.ToInt32( HybridConfig.GetAppSetting("TimestampExpiry"));
- int i = OperationContext.Current.IncomingMessageHeaders.FindHeader("Timestamp", ns);
- //If timestamp is not set in the header
- if(i==-1)
- throw new FaultException("Invalid Request.Timestamp is not set");
- string timestamp = OperationContext.Current.IncomingMessageHeaders.GetHeader<string>(i);
- //if timestamp header doesnot contain any data
- if (string.IsNullOrEmpty(timestamp))
- throw new FaultException("Invalid Request.Timestamp is not set");
- DateTime timeStampValue = Convert.ToDateTime(timestamp);
- if (DateTime.UtcNow.AddSeconds(timespanExpiry) > timeStampValue)
- throw new FaultException("Invalid Request.Timestamp is expired");
- }
- }
Hope this would help.
Happy Coding !!!
This is very immense information to the developers who are in the stage of beginning in website development.
ReplyDeleteResponsive Web Design Companies | Web Designing Company Bangalore
This comment has been removed by the author.
ReplyDelete