惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

IT之家
IT之家
Engineering at Meta
Engineering at Meta
腾讯CDC
宝玉的分享
宝玉的分享
H
Help Net Security
I
InfoQ
博客园 - Franky
The GitHub Blog
The GitHub Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Microsoft Security Blog
Microsoft Security Blog
M
MIT News - Artificial intelligence
博客园_首页
美团技术团队
Recent Announcements
Recent Announcements
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
雷峰网
雷峰网
The Cloudflare Blog
博客园 - 司徒正美
Vercel News
Vercel News
MyScale Blog
MyScale Blog
人人都是产品经理
人人都是产品经理
爱范儿
爱范儿
月光博客
月光博客

博客园 - 队长

利用selenium将edge浏览器里面的网页保存为pdf DataSet 序列化时保持行状态 Netcore logging config Some good articles Microservices with Spring Boot ngrok的简单使用 - 队长 通过Ajax上传文件至WebApi服务器 Simple Pipelined Function Simple layout WebApi中利用Razor模板引擎来生成html EF DI & MVC EF UoC ks 图片 UEditor Alvin temp Assembly binding Tech Links
Spring Boot - Filter实现简单的Http Basic认证
队长 · 2017-03-05 · via 博客园 - 队长

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; 
        } 
    }