locked
How would you implement API key type security? RRS feed

  • Question

  • Is there a way that someone has to pass in an API key in the URL / or some other way of passing the service a private key in order to grant access to the data?

    I have this right now...

     

    using System;
    using System.Data.Services;
    using System.Data.Services.Common;
    using System.Collections.Generic;
    using System.Linq;
    using System.ServiceModel.Web;
    using Numina.Framework;
    using System.Web;
    using System.Configuration;
    
    [System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    public class odata : DataService {
    
        
        public static void InitializeService(DataServiceConfiguration config) {
    
            config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
            //config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
        }
    
        protected override void OnStartProcessingRequest(ProcessRequestArgs args) {
    
            HttpRequest Request = HttpContext.Current.Request;
            if(Request["apikey"] != ConfigurationManager.AppSettings["ApiKey"])
                throw new DataServiceException("ApiKey needed");
    
            base.OnStartProcessingRequest(args);
        }
    }
    
    

     

    ...This works but it's not perfect because you cannot get at the metadata and discover the service through the Add Service Reference explorer. I could check if $metadata is in the url but it seems like a hack. Is there a better way?

    Saturday, March 20, 2010 4:06 AM

Answers

  • Hi,

    Your solutions is probably as good as it gets by now. I'm not aware of a better way of doing this. If you need to only allow/disallow certain parts of your service you usually use query interceptors or so. But for the $metadata I think the only way is to look for the "$metadata" in the URL.

    Thanks,


    Vitek Karas [MSFT]
    Saturday, March 20, 2010 12:52 PM
    Moderator