Click here to Skip to main content
Click here to Skip to main content

Tagged as

WCF REST 4.0 Authorization with Form Based authentication (SetAuthCookie)

, 25 Dec 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
How to create custom authorization policy and return HTTPContext Identity for Authorization
This is an old version of the currently published article.


Windows Communication Foundation provides tons of methods to authenticate users' check for authorization based on service type that it's quite confusing to implement simple form based authentication and role based authorization for WCF REST 4.0.

Note: This article assumes that WCF REST service is hosted with ASP.NET application and shares the same web.config. Make sure that Form Authentication is enabled in web.config file.


There are many ways to authenticate and authorize user in WCF Service, but in this example, authentication cookie will already be created by login page and that will be used by subsequent requests made to REST service for authorization.

Using the Code

A typical way to authorize user for specific role is to use Principal Permission attribute. Something like this:

WebGet(UriTemplate = "")]
[PrincipalPermission(SecurityAction.Demand, Role="Admin")]
public List<SampleItem> GetCollection(){} 

But even though after user is authenticated using Membership provider and HTTPContext.Current.User.Identity and the context is available at service level, the principal permission attribute always throws a security exception.

The reason for that is because principal permission attribute checks for System.Threading.Thread.CurrentPrincipal.Identity and not for HTTPContext Identity.

To solve this problem, we have to create a Custom Principal and Authorization Policy for WCF Service. Then this Policy will be hooked with WCF REST Service using ServiceBehaviour.

Custom Principal

Here is the code for custom principal:

 public class CustomPrincipal: IPrincipal
        private IIdentity _identity;
        public IIdentity Identity
                return _identity;

        public CustomPrincipal(IIdentity identity)
            _identity = identity;           

        public bool IsInRole(string role)
            return Roles.IsUserInRole(role);

Here AspNet Membership Role provider is used to verify if the user is in a particular role for not. We can have our custom implementation that does not user Membership provider.

Authorization Policy

Now create Authorization policy that sets the Custom Principal to the evaluation context:

public class AuthorizationPolicy : IAuthorizationPolicy
        string id = Guid.NewGuid().ToString();

        public string Id
            get { return; }

        public System.IdentityModel.Claims.ClaimSet Issuer
            get { return System.IdentityModel.Claims.ClaimSet.System; }

        // this method gets called after the authentication stage
        public bool Evaluate(EvaluationContext evaluationContext, ref object state)
            // get the authenticated client identity
            IIdentity client = HttpContext.Current.User.Identity; 
            // set the custom principal
            evaluationContext.Properties["Principal"] = new CustomPrincipal(client);

            return true;

If you look closely, the custom principal is created using HTTPContext Identity that was created after user is authenticated using membership provider and authentication cookie is set after validating the user. Something like this:

FormsAuthentication.SetAuthCookie(username, false);

Attach Authorization Policy to the WCF

This can be done by creating service behavior in web.config file. But here, I have created custom service behavior by implementing IServiceBehavior and attach the authorization policy to it.

public class SecurityBehaviorAttribute : Attribute, IServiceBehavior
    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, 
    	System.ServiceModel.ServiceHostBase serviceHostBase)
        List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>();
        policies.Add(new AuthorizationPolicy());
        serviceHostBase.Authorization.ExternalAuthorizationPolicies = 

        ServiceAuthorizationBehavior bh =
        if (bh != null)
            bh.PrincipalPermissionMode = PrincipalPermissionMode.Custom;
            throw new NotSupportedException();

    public void AddBindingParameters(ServiceDescription serviceDescription, 
    	System.ServiceModel.ServiceHostBase serviceHostBase, 
    	System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, 
    	System.ServiceModel.Channels.BindingParameterCollection bindingParameters) { }

    public void Validate(ServiceDescription serviceDescription, 
    	System.ServiceModel.ServiceHostBase serviceHostBase) { }

Here, ServiceAuthorizationBehavior PrincipalPermissionMode is set to Custom and Authorization policy is added to the servicehost.

Service Code

Make sure that service behavior is added as attribute to the service class.

    [AspNetCompatibilityRequirements(RequirementsMode = 
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class Service1  {
        [WebGet(UriTemplate = "")]
        [PrincipalPermission(SecurityAction.Demand, Role="Admin")]
        public List<SampleItem> GetCollection()
            var value =  System.Web.HttpContext.Current.User.Identity.IsAuthenticated;
            return new List<SampleItem>() { new SampleItem() 
				{ Id = 1, StringValue = "Hello" } };

That's all. Now we can add PrincipalPermission attribute to any web method and authorize user for specific role. We can also implement custom PrincipalPermission attribute to control the granularity of authorization.

Note: We can also create Authentication service to validate user name password and create authentication cookie after validation. Here, the assumption is that WCF REST is hosted with Web application and therefore shares the context.

Let me know if there is any better way to achieve the same thing without providing user name and password at each request.


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


About the Author

India India
I work as a freelance consultant and is passionate about taking challenges in latest technology.
I am a solution architect and trainer with 9+ years experience in designing, developing and maintaining enterprise wide application using latest technology like SharePoint 2010, MOSS 2007, Business Intelligence, SQL Server 2008, Reporting Service, Analysis Service and Integration service.

Comments and Discussions

Discussions posted for the Published version of this article. Posting a message here will take you to the publicly available article in order to continue your conversation in public.
GeneralMy vote of 2 PinprofessionalNirosh20-Jun-14 0:18 
Questionsome difficulty implementing Pinmembernoncitizen2-Jun-14 5:04 
AnswerRe: some difficulty implementing PinmemberAnupama_Agarwal2-Jun-14 6:34 
GeneralRe: some difficulty implementing Pinmembernoncitizen3-Jun-14 5:41 
AnswerRe: some difficulty implementing Pinmembernoncitizen3-Jun-14 5:32 
GeneralRe: some difficulty implementing PinmemberAnupama_Agarwal3-Jun-14 19:37 
GeneralMy vote of 1 Pinmemberdave_dv7-Oct-13 4:25 
QuestionRequest for principal permission failed Pinmemberyahav_g16-Jul-13 0:51 
QuestionThanks!! Pinmemberpaulopez27-Apr-13 0:06 
GeneralMy vote of 5 PinmemberPrasad Khandekar20-Mar-13 23:19 
QuestionVisual Studio 2012 PinmemberNejimon CR19-Mar-13 8:38 
AnswerRe: Visual Studio 2012 PinmemberAnupama_Agarwal22-Mar-13 22:13 
GeneralRe: Visual Studio 2012 PinmemberNejimon CR23-Mar-13 5:41 
QuestionLogin as service Pinmembershivendra.kush15-Feb-13 19:28 
AnswerRe: Login as service PinmemberAnupama_Agarwal22-Mar-13 22:12 
QuestionNice solution PinmemberAbbath134924-Dec-12 8:00 
AnswerRe: Nice solution PinmemberAnupama_Agarwal25-Dec-12 9:37 
Questiongood solution! Pinmemberantares763-Dec-12 1:35 
GeneralMy vote of 5 Pinmembersandippatil19-Sep-12 22:45 
GeneralMy vote of 5 Pinmembermrwh12-Apr-12 11:48 
GeneralSimple Authentication implementation PinmemberMember 4049653-Jan-12 20:29 
GeneralMy vote of 5 Pinmembernilu200426-Dec-11 2:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141216.1 | Last Updated 25 Dec 2011
Article Copyright 2011 by Anupama_Agarwal
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid