Search code examples
javaauthenticationbasic-authenticationshiro

Shiro with HTTP Basic Auth or Anonymous access to same URI


I've a set of APIs under /api. If my shiro.ini lists this as:

/api/** = authcBasic

Then basic auth is required. If anon is present in place of authcBasic then no auth is required. I'd like to be able to use the APIs with basic auth so I can e.g. programatically check the user is authenticated for POSTs and yet still allow anonymous access to GETs on the same URI. Alternatively to hide restricted data at the same URI for anonymous users and reveal it for auth'd users.

Is this possible?


Solution

  • You can roll your own custom shiro filter. Extend class BasicHttpAuthenticationFilter and override onPreHandle where you can check the servlet request method if it is GET or POST and act on it.

    So something like:

    public class MyFilter extends BasicHttpAuthenticationFilter {
    
        @Override
        protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) {
            if ("GET".equals((HttpServletRequest)request).getMethod()){
                return true;
            }
            return super.onPreHandle(request, response, mappedValue);
        }
    
    }
    

    And in shiro.ini:

    [main]
    myfilter = mypackage.MyFilter
    
    [urls]
    /api/** = myfilter