if (context.isAuthenticated()) {
return new Authenticator.Success(context.getPrincipal());
}
// No previous authentication so time to continue the process.
Headers requestHeaders = httpExchange.getRequestHeaders();
if (requestHeaders.containsKey(AUTHORIZATION_HEADER) == false) {
Headers responseHeaders = httpExchange.getResponseHeaders();
responseHeaders.add(WWW_AUTHENTICATE_HEADER, CHALLENGE + " " + createChallenge(false));
return new Authenticator.Retry(UNAUTHORIZED);
}
String authorizationHeader = requestHeaders.getFirst(AUTHORIZATION_HEADER);
if (authorizationHeader.startsWith(CHALLENGE + " ") == false) {
throw MESSAGES.invalidAuthorizationHeader();
}
String challenge = authorizationHeader.substring(CHALLENGE.length() + 1);
Map<String, String> challengeParameters = parseDigestChallenge(challenge);
// Validate Challenge, expect one of 3 responses VALID, INVALID, STALE
HttpPrincipal principal = validateUser(httpExchange, challengeParameters);
// INVALID - Username / Password verification failed - Nonce is irrelevant.
if (principal == null) {
if (challengeParameters.containsKey(NONCE)) {
nonceFactory.useNonce(challengeParameters.get(NONCE));
}
Headers responseHeaders = httpExchange.getResponseHeaders();
responseHeaders.add(WWW_AUTHENTICATE_HEADER, CHALLENGE + " " + createChallenge(false));
return new Authenticator.Retry(UNAUTHORIZED);
}
// VALID - Verified username and password, Nonce is correct.
if (nonceFactory.useNonce(challengeParameters.get(NONCE))) {
context.principal = principal;
return new Authenticator.Success(principal);
}
// STALE - Verification of username and password succeeded but Nonce now stale.
Headers responseHeaders = httpExchange.getResponseHeaders();
responseHeaders.add(WWW_AUTHENTICATE_HEADER, CHALLENGE + " " + createChallenge(true));
return new Authenticator.Retry(UNAUTHORIZED);
}