Skip to content

Instantly share code, notes, and snippets.

@zonia3000
Last active July 13, 2018 00:31
Show Gist options
  • Save zonia3000/67d5a98ed46c0850318fc8eba4a006fe to your computer and use it in GitHub Desktop.
Save zonia3000/67d5a98ed46c0850318fc8eba4a006fe to your computer and use it in GitHub Desktop.
Basic-Authentication Servlet Filter
/**
* Some credits to http://stackoverflow.com/a/18363307/771431
*/
public class MyBasicAuthFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        boolean authorized = false;

        String authHeader = req.getHeader("Authorization");
        if (authHeader != null) {

            String[] authHeaderSplit = authHeader.split("\\s");

            for (int i = 0; i < authHeaderSplit.length; i++) {
                String token = authHeaderSplit[i];
                if (token.equalsIgnoreCase("Basic")) {

                    String credentials = new String(Base64.getDecoder().decode(authHeaderSplit[i + 1]));
                    int index = credentials.indexOf(":");
                    if (index != -1) {
                        String username = credentials.substring(0, index).trim();
                        String password = credentials.substring(index + 1).trim();
                        authorized = username.equals("<username>") && password.equals("<password>");
                    }
                }
            }
        }

        if (!authorized) {
            res.setHeader("WWW-Authenticate", "Basic realm=\"Insert credentials\"");
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void destroy() {
    }
}

On web.xml

<filter>
    <filter-name>MyFilterName</filter-name>
    <filter-class>my.package.MyBasicAuthFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>MyFilterName</filter-name>
    <url-pattern>/my/path/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
    <dispatcher>ERROR</dispatcher>
</filter-mapping>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment