Thursday, June 28, 2012

OData Service Custom Security

I need to create an Odata service POC that allows to return result only to authenticated users. I google about authentication with OData and found that there are many options like

1.Windows Auth
2.Forms Auth
3.Claim based Auth
4.Anonymous Auth

what i needed is much simple and easy that is somehome related to claim based auth. i have configured a QueryInterceptor on VwUsers to check token parameter and if found return the result otherwise return error. i have used Query String to get the token you can experiment this with http headers as well.


In web.config you have to set

authentication mode="off" in authentication element

This will be the service code:


 public class CareService : DataService<NorthwindEntities>

    {

        // This method is called only once to initialize service-wide policies.

        public static void InitializeService(DataServiceConfiguration config)

        {

            // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.

            // Examples:

            // config.SetEntitySetAccessRule("MyEntityset", EntitySetRights.AllRead);

            // config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All);

           

            config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);

            //Set a reasonable paging site

            //config.SetEntitySetPageSize("*", 25);

            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;

        }

        [QueryInterceptor("VwUsers")]

        public Expression&gt; OnQueryVwUsersHeaders()
        {
            var request = HttpContext.Current.Request;
            if (!string.IsNullOrEmpty(request.QueryString["token"]))
            {

   

               //token verification here

                return (VwUser p) =&gt; true;

            }

            else

            {

                throw new DataServiceException(401,

                 "The user does not have permission to view Users");

                //return (VwUser p) =&gt; false;

            }

        }

    }

No comments: