cc.protea.foundation.util.BasicAuthenticationUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of foundation Show documentation
Show all versions of foundation Show documentation
Integrate compatible versions of many external systems to create a REST/HTTP server foundation
package cc.protea.foundation.util;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.container.ContainerRequestContext;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
public class BasicAuthenticationUtil {
public static interface BasicIdentification {
public String getUsername();
public String getPassword();
}
public static BasicIdentification getIdentification(final ContainerRequestContext requestContext) {
final String url = requestContext.getUriInfo().getBaseUri().toString();
BasicIdentification identification = BasicAuthenticationUtil.getIdentificationFromUrl(url);
if (identification != null) {
return identification;
}
return BasicAuthenticationUtil.getIdentificationFromHeader(requestContext.getHeaderString("Authorization"));
}
public static BasicIdentification getIdentification(final HttpServletRequest hsr) {
BasicIdentification identification = BasicAuthenticationUtil.getIdentificationFromUrl(hsr.getRequestURL().toString());
if (identification != null) {
return identification;
}
return BasicAuthenticationUtil.getIdentificationFromHeader(hsr.getHeader("Authorization"));
}
public static BasicIdentification getIdentificationFromUrl(final String uri) {
final Pattern urlPattern = Pattern.compile("(ftp|sftp)://(\\S+):(\\S+)@([\\S&&[^:]]+)(:(\\d+))?");
final Matcher m = urlPattern.matcher(uri);
if(! m.matches()) {
return null;
}
final String user = m.group(2);
final String pass = m.group(3);
return new BasicIdentification() {
public String getUsername() { return user; }
public String getPassword() { return pass; }
};
}
public static BasicIdentification getIdentificationFromHeader(final String header) {
if (header == null || ! StringUtils.startsWith(header, "Basic ")) {
return null;
}
final String encodedUserPassword = header.replaceFirst("Basic ", "");
return BasicAuthenticationUtil.getIdentificationFromPassword(encodedUserPassword);
}
public static BasicIdentification getIdentificationFromPassword(final String encodedUserPassword) {
final String usernameAndPassword = new String(Base64.decodeBase64(encodedUserPassword.getBytes()));
final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
final String user = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
final String pass = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
return new BasicIdentification() {
public String getUsername() { return user; }
public String getPassword() { return pass; }
};
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy