001/**
002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com).
003 * <p>
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * <p>
008 * http://www.apache.org/licenses/LICENSE-2.0
009 * <p>
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package io.jboot.support.shiro;
017
018import org.apache.shiro.web.env.WebEnvironment;
019import org.apache.shiro.web.filter.mgt.FilterChainResolver;
020import org.apache.shiro.web.servlet.ShiroFilter;
021import org.apache.shiro.web.util.WebUtils;
022
023import javax.servlet.FilterChain;
024import javax.servlet.ServletException;
025import javax.servlet.ServletRequest;
026import javax.servlet.ServletResponse;
027import javax.servlet.http.HttpServletRequest;
028import javax.servlet.http.HttpServletResponse;
029import java.io.IOException;
030
031/**
032 * @author Michael Yang 杨福海 (fuhai999@gmail.com)
033 * @version V1.0
034 */
035public class JbootShiroFilter extends ShiroFilter {
036
037    private int contextPathLength = 0;
038
039    @Override
040    public void init() throws Exception {
041        WebEnvironment env = WebUtils.getRequiredWebEnvironment(getServletContext());
042
043        if (env.getServletContext().getContextPath() != null) {
044            contextPathLength = env.getServletContext().getContextPath().length();
045        }
046
047        setSecurityManager(env.getWebSecurityManager());
048
049        FilterChainResolver resolver = env.getFilterChainResolver();
050        if (resolver != null) {
051            setFilterChainResolver(resolver);
052        }
053    }
054
055    @Override
056    protected void doFilterInternal(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {
057        HttpServletRequest request = (HttpServletRequest) servletRequest;
058        HttpServletResponse response = (HttpServletResponse) servletResponse;
059
060        String target = request.getRequestURI();
061        if (contextPathLength != 0) {
062            target = target.substring(contextPathLength);
063        }
064
065        if (target.indexOf('.') != -1) {
066            chain.doFilter(request, response);
067            return;
068        }
069
070        super.doFilterInternal(request, response, chain);
071    }
072}