Wednesday, 4 April 2012

Wcf REST Authentication:-

In wcf REST starter kit we get Microsoft.ServiceModel.Web dll file which gives features like throwing exceptions and authentication.

Instead of writing  authentication code on each function we can use the wcfREST starter kit  RequestInterceptor class.

->Create wcf REST service.

    public class Service
        [WebGet(ResponseFormat = WebMessageFormat.Json)]
        public string SayHello(string name)
            //Return string.
            return "Hello " + name;
    public class Error
        public string Message { get; set; }

->Add new class AuthenticationInterceptor and inherit it from RequestInterceptor
class and override ProcessRequest method.
public class AuthenticationInterceptor : RequestInterceptor
        public AuthenticationInterceptor()
            : base(false)
        public override void ProcessRequest(ref System.ServiceModel.Channels.RequestContext requestContext)
            //Get the message object from the request context.
            Message msg = requestContext.RequestMessage;
            HttpRequestMessageProperty rmp = (HttpRequestMessageProperty)msg.Properties[HttpRequestMessageProperty.Name];

            //Get the list of query strings.
            NameValueCollection nmc = HttpUtility.ParseQueryString(rmp.QueryString);

            //Get the userId from the query string collection.
            string userId = nmc["UserId"];

            //Check the user id.
            if (userId != "Admin")
                //If the user is not the Admin then generate the error response.
                GenerateErrorResponse(requestContext, HttpStatusCode.Unauthorized, "Please provide valid user id.");
               //Set the requestcontext to null to send the message.
               requestContext = null;

        //Generate the error response to the client.
        public void GenerateErrorResponse(RequestContext requestContext, HttpStatusCode statusCode, string errorMessage)
            //Create error object.
            Error objError = new Error();

            //Set the error message.
            objError.Message = errorMessage;

            //Create message object.
            Message reply = Message.CreateMessage(MessageVersion.None, "", objError, new DataContractJsonSerializer(typeof(Error)));

            //Set the response type to json.
            HttpResponseMessageProperty responseProp = new HttpResponseMessageProperty();
            responseProp.StatusCode = statusCode;
            responseProp.Headers[HttpResponseHeader.ContentType] = "application/json";
            reply.Properties[HttpResponseMessageProperty.Name] = responseProp;

            WebBodyFormatMessageProperty formatMessageProperty = new WebBodyFormatMessageProperty(WebContentFormat.Json);
            reply.Properties[WebBodyFormatMessageProperty.Name] = formatMessageProperty;

            //Replies to a request message.

->Add the above AuthenticationInterceptor to the ServiceHost.

<%@ ServiceHost Language="C#" Debug="true" Service="WcfRestAuthentication.Service" CodeBehind="Service.svc.cs" Factory="WcfRestAuthentication.HostFactory"%>

using Microsoft.ServiceModel.Web;
using System.ServiceModel;

namespace WcfRestAuthentication
    public class HostFactory : WebServiceHost2Factory
        protected override ServiceHost CreateServiceHost(System.Type serviceType, System.Uri[] baseAddresses)
            //Create WebServiceHost2 object with serviceType and baseAddresses.
            WebServiceHost2 host = new WebServiceHost2(serviceType, true, baseAddresses);

            //Add AuthenticationInterceptor to host.
            host.Interceptors.Add(new AuthenticationInterceptor());
            //Return host object.
            return host;

Let me know, if you have any feedback. Mail me for source code. Enjoy reading my articles…

No comments:

Post a Comment