Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I authenticate a WCF Data Service?

I've created an ADO.Net WCF Data Service hosted in a Azure worker role. I want to pass credentials from a simple console client to the service then validate them using a QueryInterceptor. Unfortunately, the credentials don't seem to be making it over the wire.

The following is a simplified version of the code I'm using, starting with the DataService on the server:

using System;
using System.Data.Services;
using System.Linq.Expressions;
using System.ServiceModel;
using System.Web;

namespace Oslo.Worker
{
    [ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
    public class AdminService : DataService<OsloEntities>
    {
        public static void InitializeService(
            IDataServiceConfiguration config)
        {
            config.SetEntitySetAccessRule("*", EntitySetRights.All);
            config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
        }

        [QueryInterceptor("Pairs")]
        public Expression<Func<Pair, bool>> OnQueryPairs()
        {
            // This doesn't work!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            if (HttpContext.Current.User.Identity.Name != "ADMIN")
                throw new Exception("Ooops!");

            return p => true;
        }
    }
}

Here's the AdminService I'm using to instantiate the AdminService in my Azure worker role:

using System;
using System.Data.Services;

namespace Oslo.Worker
{
    public class AdminHost : DataServiceHost
    {
        public AdminHost(Uri baseAddress)
            : base(typeof(AdminService), new Uri[] { baseAddress })
        {
        }
    }
}

And finally, here's the client code.

using System;
using System.Data.Services.Client;
using System.Net;
using Oslo.Shared;

namespace Oslo.ClientTest
{
    public class AdminContext : DataServiceContext
    {
        public AdminContext(Uri serviceRoot, string userName,
            string password) : base(serviceRoot)
        {
            Credentials = new NetworkCredential(userName, password);
        }

        public DataServiceQuery<Order> Orders
        {
            get
            {
                return base.CreateQuery<Pair>("Orders");
            }
        }
    }
}

I should mention that the code works great with the signal exception that the credentials are not being passed over the wire.

Any help in this regard would be greatly appreciated!

Thanks....

like image 346
Louis S. Berman Avatar asked May 17 '10 18:05

Louis S. Berman


1 Answers

You must throw an exception of type DataServiceException.

like image 134
Rush Frisby Avatar answered Oct 12 '22 02:10

Rush Frisby