Spring Boot - Filter实现简单的Http Basic认证

Posted teamleader

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot - Filter实现简单的Http Basic认证相关的知识,希望对你有一定的参考价值。

Copy自http://blog.csdn.net/sun_t89/article/details/51916834

@SpringBootApplication
public class SpringRestApplication { 
public static void main(String[] args) { 
        SpringApplication.run(SpringRestApplication.class, args); 
    } 
@Bean
public FilterRegistrationBean  filterRegistrationBean() { 
        FilterRegistrationBean registrationBean = new FilterRegistrationBean(); 
        HTTPBasicAuthorizeAttribute httpBasicFilter = new HTTPBasicAuthorizeAttribute(); 
        registrationBean.setFilter(httpBasicFilter); 
        List<String> urlPatterns = new ArrayList<String>(); 
        urlPatterns.add("/user/*"); 
        registrationBean.setUrlPatterns(urlPatterns); 
return registrationBean; 
    } 

public class HTTPBasicAuthorizeAttribute implements Filter{
    private static String Name = "test";
    private static String Password = "test";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // TODO Auto-generated method stub
       
        ResultStatusCode resultStatusCode = checkHTTPBasicAuthorize(request);
        if (resultStatusCode != ResultStatusCode.OK)
        {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setCharacterEncoding("UTF-8"); 
            httpResponse.setContentType("application/json; charset=utf-8");
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

            ObjectMapper mapper = new ObjectMapper();
           
            ResultMsg resultMsg = new ResultMsg(ResultStatusCode.PERMISSION_DENIED.getErrcode(), ResultStatusCode.PERMISSION_DENIED.getErrmsg(), null);
            httpResponse.getWriter().write(mapper.writeValueAsString(resultMsg));
            return;
        }
        else
        {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub       
    }   

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }


    private ResultStatusCode checkHTTPBasicAuthorize(ServletRequest request)
    {
        try
        {
            HttpServletRequest httpRequest = (HttpServletRequest)request;
            String auth = httpRequest.getHeader("Authorization");
            if ((auth != null) && (auth.length() > 6))
            {
                String HeadStr = auth.substring(0, 5).toLowerCase();
                if (HeadStr.compareTo("basic") == 0)
                {
                    auth = auth.substring(6, auth.length()); 
                    String decodedAuth = getFromBASE64(auth);
                    if (decodedAuth != null)
                    {
                        String[] UserArray = decodedAuth.split(":");
                       
                        if (UserArray != null && UserArray.length == 2)
                        {
                            if (UserArray[0].compareTo(Name) == 0
                                    && UserArray[1].compareTo(Password) == 0)
                            {
                                return ResultStatusCode.OK;
                            }
                        }
                    }
                }
            }
            return ResultStatusCode.PERMISSION_DENIED;
        }
        catch(Exception ex)
        {
            return ResultStatusCode.PERMISSION_DENIED;
        }       
    }
   
    private String getFromBASE64(String s) { 
        if (s == null) 
            return null; 
        BASE64Decoder decoder = new BASE64Decoder(); 
        try { 
            byte[] b = decoder.decodeBuffer(s); 
            return new String(b); 
        } catch (Exception e) { 
            return null; 
        } 
    }





























































































以上是关于Spring Boot - Filter实现简单的Http Basic认证的主要内容,如果未能解决你的问题,请参考以下文章

spring boot filter实现

Spring Boot参考教程Spring Boot配置Servlet,Filter,Listener,Interceptor

spring boot filter -Autowired

Spring Boot (Filter)过滤器的实现以及使用场景

Spring Boot 实战:如何自定义 Servlet Filter

在spring boot框架下开发dubbo filter