Skip to content

Instantly share code, notes, and snippets.

@tbk303
Created December 7, 2010 17:41
Show Gist options
  • Save tbk303/732127 to your computer and use it in GitHub Desktop.
Save tbk303/732127 to your computer and use it in GitHub Desktop.
BasicAuthFilter.java
package name.tbh.tools.servlet;
import java.io.IOException;
import javax.annotation.Nonnull;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import com.google.common.base.Charsets;
/**
* A very simple Servlet Filter for HTTP Basic Auth. Only supports exactly one user
* with a password. Please note, HTTP Basic Auth is not encrypted and hence unsafe!
*
* @author Timo B. Huebel (me@tbh.name) (initial creation)
*/
public class BasicAuthFilter implements Filter {
public static final String PARAM_USER = "user";
public static final String PARAM_PASSWORD = "password";
public static final String PARAM_REALM = "realm";
private String _user;
private String _password;
private String _realm;
@Override
public void destroy() {
// Nothing to do.
}
@Override
public void doFilter( @Nonnull final ServletRequest request, @Nonnull final ServletResponse response,
@Nonnull final FilterChain chain ) throws IOException, ServletException {
final HttpServletRequest httpRequest = (HttpServletRequest) request;
final HttpServletResponse httpResponse = (HttpServletResponse) response;
final String auth = httpRequest.getHeader( "Authorization" );
if ( auth != null ) {
final int index = auth.indexOf( ' ' );
if ( index > 0 ) {
final String[] credentials =
StringUtils.split( new String( Base64.decodeBase64( auth.substring( index ) ), Charsets.UTF_8 ), ':' );
if ( credentials.length == 2 && _user.equals( credentials[0] ) && _password.equals( credentials[1] ) ) {
chain.doFilter( httpRequest, httpResponse );
return;
}
}
}
httpResponse.setHeader( "WWW-Authenticate", "Basic realm=\"" + _realm + "\"" );
httpResponse.sendError( HttpServletResponse.SC_UNAUTHORIZED );
}
@Override
public void init( @Nonnull final FilterConfig config ) throws ServletException {
_user = config.getInitParameter( PARAM_USER );
_password = config.getInitParameter( PARAM_PASSWORD );
_realm = config.getInitParameter( PARAM_REALM );
if ( StringUtils.isBlank( _user ) ) {
throw new ServletException( "No user provided in filter configuration" );
}
if ( StringUtils.isBlank( _password ) ) {
throw new ServletException( "No password provided in filter configuration" );
}
if ( StringUtils.isBlank( _realm ) ) {
throw new ServletException( "No realm provided in filter configuration" );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment