Java – is there a server independent way to implement basic authentication?
I'm trying to add basic authentication to my restful web service At present, I perform basic authentication on Apache Tomcat 6.0 server, but I need to deploy my web service on websphere application server 6.1 and I encountered problems running basic authentication on WebSphere
Is there a way to check the authentication header of HTTP request in Java? If the user name / password provided (encoded in Base64) does not match the known account, the user enters a new user name / password?
I've tried to implement spring security, but since my project doesn't have spring at all, trying to make it work is a great pain. I'm trying to find a simple solution to my fairly simple problem
The technologies I currently use include: Java, Jersey / jax-rs, eclipse with Maven plug-in
Solution
You should be able to set up a servlet filter that executes before the rest handler, check the "authorization" request header, base 64 decodes it, extract the user name and password, and verify it Something like this:
public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) {
if (request instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest) req;
String authHeader = Base64.decode(request.getHeader("Authorization"));
String creds[] = authHeader.split(":");
String username = creds[0],password = creds[1];
// Verify the credentials here...
if (authorized) {
chain.doFilter(req,res,chain);
} else {
// Respond 401 Authorization required.
}
}
doFilter(req,chain);
}
All servlet containers have a standard way to configure filter chains
