Click here to Skip to main content
15,896,269 members
Articles / Programming Languages / XML

WCF - Authentication and Authorization in Enterprise Architecting

Rate me:
Please Sign up or sign in to vote.
4.79/5 (25 votes)
20 Jun 2012CPOL13 min read 124.5K   4.5K   95  
How to expose a WCF Service Application along with Authentication Service and Authorization according to Enterprise Architecting standards.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.Net;
using System.IO;
using System.ServiceModel;
using System.Security.Principal;
using System.Web.Security;
using System.Threading;
using System.Collections;

namespace WCFService
{
    public class IdentityMessageInspector : IDispatchMessageInspector
    {
        public object AfterReceiveRequest(ref Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            var messageProperty = (HttpRequestMessageProperty)
                OperationContext.Current.IncomingMessageProperties[HttpRequestMessageProperty.Name];
            string cookie = messageProperty.Headers.Get("Set-Cookie");
            if (cookie == null) // Check for another Message Header - SL applications
            {
                cookie = messageProperty.Headers.Get("Cookie");
            }
            if (cookie == null)
                cookie = string.Empty;

            Hashtable cookieTable = new Hashtable();
            string[] cookieValuePairs = cookie.Split(';');
            foreach (string pair in cookieValuePairs)
            {
                string[] splitted = pair.Split(',', '=');
                string key = splitted[0].Trim();

                if (splitted.Length >= 2)
                    if (!cookieTable.ContainsKey(key))
                        cookieTable.Add(key, splitted[1]);
            }

            string encryptedTicket = string.Empty;

            // Set User Name from cookie
            if (cookieTable.ContainsKey(FormsAuthentication.FormsCookieName))
                encryptedTicket = cookieTable[FormsAuthentication.FormsCookieName].ToString();

            FormsAuthenticationTicket ticket = null;
            string userName = string.Empty;
            string roles = string.Empty;

            // Decrypt
            if (!string.IsNullOrEmpty(encryptedTicket))
            {
                ticket = FormsAuthentication.Decrypt(encryptedTicket);
                userName = ticket.Name;
                roles = ticket.UserData;
            }

            // Set Thread Principal to User Name
            if (!string.IsNullOrEmpty(userName))
            {
                CustomIdentity customIdentity = new CustomIdentity();
                GenericPrincipal threadCurrentPrincipal = new GenericPrincipal(customIdentity, roles.Split(','));
                customIdentity.IsAuthenticated = true;
                customIdentity.Name = userName;
                Thread.CurrentPrincipal = threadCurrentPrincipal;
            }

            return null;
        }

        private string[] GetRoles(string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                List<string> roles = new List<string>();

                int ix = 0;
                foreach (string item in value.Split(';'))
                {
                    if (ix > 0)
                        if (item.Trim().Length > 0)
                            roles.Add(item);

                    ix++;
                }

                return roles.ToArray<string>();
            }

            return new string[0];
        }

        private string GetUserName(string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                foreach (string item in value.Split(';'))
                    return item;
            }

            return string.Empty;
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {

        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
United States United States
Jean Paul is a Microsoft MVP and Architect with 12+ years of experience. He is very much passionate in programming and his core skills are SharePoint, ASP.NET & C#.

In the academic side he do hold a BS in Computer Science & MBA. In the certification side he holds MCPD & MCTS spanning from .Net Fundamentals to SQL Server.

Most of the free time he will be doing technical activities like researching solutions, writing articles, resolving forum problems etc. He believes quality & satisfaction goes hand in hand.

You can find some of his work over here. He blogs at http://jeanpaulva.com

Comments and Discussions