using System; using System.Configuration; using System.Web.Services; using ZetaLib.Core.Common; using ZetaLib.Core.Collections; /// /// Base class for web services that protect their functions with /// an API key. /// public class ApiKeyProtectedWebServiceBase : WebService { /// /// /// private static string[] validApiKeys { get { if ( _validApiKeys == null ) { lock ( typeLock ) { Set result = new Set(); result.AddRange( ConvertHelper.ToString( ConfigurationManager.AppSettings[ apiKeyConfigName], string.Empty ).Split( new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries ) ); _validApiKeys = result.ToArray(); } } return _validApiKeys; } } /// /// Checks whether the API key is valid. /// protected static void CheckApiKey( string apiKey ) { if ( validApiKeys.Length > 0 ) { foreach ( string validApiKey in validApiKeys ) { if ( string.Compare( apiKey, validApiKey, true ) == 0 ) { return; } } // Invalue. throw new ApplicationException( string.Format( "Invalid API key '{0}'.", apiKey ) ); } } private static string apiKeyConfigName = @"apiKey"; /// /// Allows for changing the app settings key. /// protected static string ApiKeyConfigName { get { lock ( typeLock ) { return apiKeyConfigName; } } set { lock ( typeLock ) { if ( apiKeyConfigName != value ) { apiKeyConfigName = value; _validApiKeys = null; } } } } private static string[] _validApiKeys; private static object typeLock = new object(); }