title: Java HttpURLConnection automaticlly attach authentication header when return code 401
body: <p>I am trying to implement HTTP Kerberos authentication for my client application, after compare available solutions I decide to use JNA to fetch Kerberos ticket through Windows SSPI, and it works well if I manually attach the Kerberos ticket to each <code>HttpUrlConnection</code>:</p>
  
  <pre><code>req.addRequestProperty("Authorization", "Negotiate " + ticket);
  </code></pre>
  
  <p>But I know that the JAAS way of Kerberos authentication does not require this manual authentication header attach step, it will automatically handle a 401 response with Negotiate scheme, and re-send the request with authentication header attached. You just send a normal <code>HttpUrlConnection</code> and don't need to worry about authentication and ticket part.</p>
  
  <p>So what I am trying to implement is something like that, for a <code>HttpUrlConnection</code>, 1) handle the <code>401</code> response with <code>Negotiate</code> scheme, and 2) attach the authentication ticket from SSPI, and automatically re-send the request like JAAS do.</p>
  
  <p>I kind of figured out that may be I can handle the 401 with a custom <code>javax.security.auth.spi.LoginModule</code> and do the ticket fetch, but I still have no clue on how to attach the authentication and resend the request after that. Could anyone help on this?</p>
  
  <p>Thanks.</p>