Ecco un codice che restituisce un oggetto Credential (oggetto bean che contiene login e password).
public Credentials credentialsWithBasicAuthentication(HttpServletRequest req) {
String authHeader = req.getHeader("Authorization");
if (authHeader != null) {
StringTokenizer st = new StringTokenizer(authHeader);
if (st.hasMoreTokens()) {
String basic = st.nextToken();
if (basic.equalsIgnoreCase("Basic")) {
try {
String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8");
LOG.debug("Credentials: " + credentials);
int p = credentials.indexOf(":");
if (p != -1) {
String login = credentials.substring(0, p).trim();
String password = credentials.substring(p + 1).trim();
return new Credentials(login, password);
} else {
LOG.error("Invalid authentication token");
}
} catch (UnsupportedEncodingException e) {
LOG.warn("Couldn't retrieve authentication", e);
}
}
}
}
return null;
}
Funziona bene, anche con una password come funky come:? & =/E $ £.
Ecco un test di base unità per la classe, utilizzando jMock:
public void testCredentialsWithBasicAuthentication() {
// Setup
final HttpServletRequest request = context.mock(HttpServletRequest.class);
AuthentificationHelper helper = new AuthentificationHelper();
String login = "mickael";
String password = ":&=/?é$£";
String base64Hash = Base64.encodeString(login + ":" + password);
final String authHeader = "Basic " + base64Hash;
// Expectations
context.checking(new Expectations() {
{
oneOf (request).getHeader("Authorization");
will(returnValue(authHeader));
}
});
// Execute
Credentials credentials = helper.credentialsWithBasicAuthentication(request);
// Verify
assertNotNull(credentials);
assertEquals(login, credentials.getLogin());
assertEquals(password, credentials.getPassword());
context.assertIsSatisfied();
}
fonte
2013-08-21 16:50:41
Inserisci servlet –
ho appena usato il campione nel link. –
@Roy, l'esempio nel tuo post ha funzionato bene per me. Non sono sicuro del motivo per cui ti ha dato un errore. potresti aggiornare il tuo post con lo stacktrace? –