title: Authenticating to an API with a token
body: <p>I'm working with the Zendesk API, an HTTPS-only, JSON API and authentication is required to update a resource, and the API supplies an API token to use when authenticating as different users. When updating a resource, I issue a PUT request over SSL, assign the appropriate JSON content to the request body, and specify the <code>Content-Type</code> request header as <code>application/json</code>. </p>
  
  <p>Next, the API instructs its users to authenticate as the end-user by either using the user's email and password (which I can't do for several reasons) or to use the user's email address along with the API token. The following is my attempt to authorize to the API  with the Authorization header:</p>
  
  <pre><code>@id = params[:id]
  @comment_body = params[:comment]
  
  uri = URI.parse "https://{subdomain}.zendesk.com/api/v2/requests/#{@id}.json"
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  req = Net::HTTP::Put.new(uri.request_uri)
  req.body = '{"request": {"comment":{"value":' + "\"#{@comment_body}\"" + '}}}'
  req['Content-Type'] = 'application/json'
  
  #The following two lines do not work!
  credentials = Base64::encode64("{user_email}/token:{api_token}")
  request.headers['Authorization'] = "Basic #{credentials}"
  
  response = http.request(req)
  </code></pre>
  
  <p>The API specifies that the format for authentication using the API token is <code>{user_email}/token:{api_token}</code>. I encoded that format with <code>Base64::encode64</code> and passed it to the Authorization Header preceded with <code>Basic</code>, but the response is a 401 Unauthorized. However, replacing those two lines with <code>req.basic_auth {user_email}, {user_password}</code> works fine. </p>
  
  <p>So my question is, how can I authenticate as a different user using the email and the given API token as authentication instead of supplying the user's email and password to <code>req.basic_auth</code>?</p>
  
  <p>The googling I've done on the topic has revealed very little; apparently it's a lot more common to use the normal <code>{username}:{password}</code> format when dealing with the Authorization header than an API token.</p>
  
  <p>Thanks in advance!!</p>
  
  <p><em>Update:</em> Weirdly, trying to authenticate as the end-user with <code>req['Authorization'] = "Basic #{credentials}"</code> does not return a 401 Unauthorized Error or a WWW-Authenticate header while trying to authorize as <code>request.headers['Authorize'] = "Basic #{credentials}"</code> does.</p>