TokenAuthorize.cs (Source)

public class TokenAuthorize : AuthorizeAttribute  
{
	private static readonly log4net.ILog log = log4net.LogManager.GetLogger("TokenAuthorize");

	public TokenAuthorize()
		: base()
	{
	}

	/// <summary>
	/// Safe against timing attacks.
	/// </summary>
	/// <param name="cmpAgainst"></param>
	/// <returns></returns>
	protected bool SafeCmp(String cmpAgainst)
	{
		var password = ConfigurationManager.AppSettings["BasicAuthAPIKey"];

		if (cmpAgainst.Length != password.Length)
			return false;

		// This loop will never short-circuit. Therefore it will always take the 
		// same amount of time. 
		int result = 0;
		for(int i = 0; i < cmpAgainst.Length; i++) {
			result |= ((byte)cmpAgainst[i]) ^ ((byte)password[i]);                
		}
		return result == 0;
	}

	protected override bool IsAuthorized(HttpActionContext httpContext)
	{   
		// Check for token in basic authentication                        
		var auth = httpContext.Request.Headers.Authorization;                        
		if(auth != null && auth.Scheme == "Basic") {
			try
			{
				var nonbase64 = Convert.FromBase64String(auth.Parameter);
				var asStr = Encoding.ASCII.GetString(nonbase64);

				log.Debug("Authorization attempt using token: " + asStr);
				return (SafeCmp(asStr));
			}
			catch (FormatException)
			{
				log.Debug("Invalid base64 format in auth: "+auth.Parameter);                   
			}
		}

		// Check for cookie as usual
		return base.IsAuthorized(httpContext);        
	}
}