title: Browser Authentication via HttpURLConnection
body: <p>Currently I am working on the implementation of <a href="http://help.themoviedb.org/kb/api/about-3" rel="nofollow">TMDb API</a>. There is a method called <a href="http://help.themoviedb.org/kb/api/user-authentication" rel="nofollow">User Authentication</a>. I have successfully implemented the Step 1</p>
  
  <blockquote>
    <p>Step 1: Generate a Request Token</p>
    
    <p>Start by making an API call to the new token method. This will return
    a new request token that will be valid for 60 minutes. The request
    token is not authorized by the user at this stage. Request tokens are
    API account specific and are the tie between your application and the
    user in step 2.</p>
  </blockquote>
  
  <p>For the step 1 I have the following code:</p>
  
  <pre><code>URL url = new URL("http://api.themoviedb.org/3/authentication/token/new?api_key=the_key");
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  StringWriter writer = new StringWriter();
  String line;
  while ((line = reader.readLine()) != null) {
      writer.write(line);
  }
  reader.close();
  Map&lt;String, List&lt;String&gt;&gt; headerFields = connection.getHeaderFields();
  String callBackUrl = null;
  for(Map.Entry&lt;String, List&lt;String&gt;&gt; entry : headerFields.entrySet()) {
      if(entry.getKey() != null &amp;&amp; entry.getKey().equals("Authentication-Callback")) {
          callBackUrl = entry.getValue().get(0);
      }
  }
  </code></pre>
  
  <p>It is printing the callback url in the console along with the Request Token (if I convert the <code>writer.toString()</code> into Json object).</p>
  
  <p>But the second part is the user authentication by their username and password. The callback url redirects user to the login page of TMDb. I have tested it by copy-pasting the callback url from console to the browser. </p>
  
  <p>The Step 2 states that:</p>
  
  <blockquote>
    <p>Step 2: Request Authorization From the User</p>
    
    <p>Once you have a valid request token, your application needs to open a
    web browser and send them to TMDb. The HTTP response when generating a
    new token will include a Authentication-Callback header that you can
    easily use for the redirect.</p>
    
    <p>If the user is not logged in to TMDb, they will be redirected to the
    login page before being asked to grant your application permission to
    use their account. Once the user has granted your application
    permission to use their account, the browser-based part of this
    process is over and you can return them to your application.</p>
    
    <p>Just like the request for a new token, the approved response will
    include a Authentication-Callback header which again, is a convenient
    way to redirect your application back to the API and generate the real
    session id.</p>
  </blockquote>
  
  <p>Now my question is: if I have the username and password, can I authenticate that user by HttpURLConnection or any other way?</p>
  
  <p>I tried this:</p>
  
  <pre><code>url = new URL(callBackUrl);
  connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod("POST");        
  BASE64Encoder encoder = new BASE64Encoder();
  String usernamepassword = "myusername" + ":" + "mypassword";
  String encodedAuthorization = encoder.encode(usernamepassword.getBytes());
  connection.setRequestProperty("Authorization", "Basic "+ encodedAuthorization);
  headerFields = connection.getHeaderFields();
  
  for(Map.Entry&lt;String, List&lt;String&gt;&gt; entry : headerFields.entrySet()) {
      System.out.println(entry.getKey() + " : " +entry.getValue());
  }
  </code></pre>
  
  <p>But in console I got:</p>
  
  <pre><code>null : [HTTP/1.1 404 Not Found]
  Status : [404 Not Found]
  X-Frame-Options : [sameorigin]
  Date : [Tue, 28 Feb 2012 08:30:17 GMT]
  Vary : [Accept-Encoding]
  X-Cascade : [pass]
  Content-Length : [7835]
  X-XSS-Protection : [1; mode=block]
  Set-Cookie : [tmdb.session=BAh7CUkiD3Nlc3Npb25faWQGOgZFRiJFNGRkMjc5ODYwMjJmYWYwZDlmOGE5%0AOTVjY2E0NWFjMzhhYTRiOGFjOGJiYjQ5ZGFhNzExNDdkMGM4MWNhZGUyMEki%0ADWxhbmd1YWdlBjsARkkiB2VuBjsARkkiC2xvY2FsZQY7AEZJIgd1cwY7AEZJ%0AIg5sb2dnZWRfaW4GOwBGRg%3D%3D%0A; path=/; expires=Thu, 29-Mar-2012 08:30:17 GMT; HttpOnly]
  Content-Type : [text/html;charset=utf-8]
  Connection : [keep-alive]
  Server : [nginx]
  </code></pre>
  
  <p>As you can see:</p>
  
  <pre><code>Status : [404 Not Found]
  </code></pre>
  
  <p>So the last procedure is not fruitful. </p>
  
  <p>Am I implementing the authentication in a wrong way?</p>
  
  <p>I really appreciate your suggestion.</p>
  
  <p>Thanks in advance.</p>