Created
April 13, 2012 09:00
-
-
Save a-thomas/2375234 to your computer and use it in GitHub Desktop.
HTTP Digest Interceptor for Spring RestTemplate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.blogtag.digest; | |
import java.io.IOException; | |
import java.util.Random; | |
import org.springframework.http.HttpHeaders; | |
import org.springframework.http.HttpRequest; | |
import org.springframework.http.client.ClientHttpRequestExecution; | |
import org.springframework.http.client.ClientHttpRequestInterceptor; | |
import org.springframework.http.client.ClientHttpResponse; | |
public class AuthHttpDigestInterceptor implements ClientHttpRequestInterceptor { | |
private final String REALM = "http-auth"; | |
private final String SEPARATOR = ", "; | |
private final String QUOTE = "\""; | |
private final String NONCE = Long.toString(new Random().nextLong(), 36); | |
private HttpHeaders headers; | |
private String username; | |
private String password; | |
public AuthHttpDigestInterceptor(String username, String password) { | |
this.username = username; | |
this.password = password; | |
} | |
@Override | |
public ClientHttpResponse intercept(HttpRequest request, byte[] data, ClientHttpRequestExecution execution) throws IOException { | |
headers = request.getHeaders(); | |
setAuthorizationHeader(request.getMethod().name(), username, password); | |
return execution.execute(request, data); | |
} | |
private void setAuthorizationHeader(String method, String username, String password) { | |
String digest1 = MD5.generate(username + ":" + REALM + ":" + password); | |
String digest2 = MD5.generate(method + ":" + "/"); | |
String digest3 = MD5.generate(digest1 + ":" + NONCE + ":" + digest2); | |
String value = "Digest " // | |
+ "username=" + QUOTE + username + QUOTE + SEPARATOR // | |
+ "realm=" + QUOTE + REALM + QUOTE + SEPARATOR // | |
+ "nonce=" + QUOTE + NONCE + QUOTE + SEPARATOR // | |
+ "uri=" + QUOTE + "/" + QUOTE + SEPARATOR // | |
+ "response=" + QUOTE + digest3 + QUOTE; | |
headers.add("authorization", value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment