admin
2022-05-19 56364722d3ed70d48ec41f567a4e59e5ccbbb868
src/main/resources/code/service/app/src/main/java/com/ks/app/config/WebSecurityConfig.java
@@ -3,10 +3,9 @@
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.ks.app.entity.AdminUser;
import com.ks.app.entity.admin.AdminUser;
import com.ks.app.service.inter.AdminUserService;
import net.sf.json.JSONObject;
import org.omg.CORBA.SystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
@@ -20,6 +19,7 @@
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
@@ -29,6 +29,7 @@
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
import org.yeshi.utils.JsonUtil;
import org.yeshi.utils.StringUtil;
@@ -46,6 +47,10 @@
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private final static String[] STATIC_RESOURCE_PATHS = new String[]{
            "/**/*.html", "/**/*.css", "/**/*.js", "/**/*.png", "/**/*.jpg", "/**/*.jpeg", "/**/*.gif", "/**/*.xml", "/**/font/*", "/**/fonts/*"
    };
    private Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);
    @Resource
@@ -53,7 +58,7 @@
    private final String LOGIN_PROCESSING_URL = "/admin/api/login";
    private final String LOGIN_PAGE_PATH="/7aed59d33d777100/login.html";
    private final String LOGIN_PAGE_PATH = "/admin/xrtfgp/login.html";
    //图形验证码配置
    @Bean
@@ -91,9 +96,16 @@
    }
    //验证码过滤器
    class VerificationCodeFilter extends OncePerRequestFilter {
        private AuthenticationFailureHandler authenticationFailureHandler = new AuthenticationFailureHandler() {
    /**
     * @author hxh
     * @description 请求之前的验证器
     * @date 16:51 2022/5/19
     * @return
     **/
    class PreRequestVerifyFilter extends OncePerRequestFilter {
        //处理验证码出错
        private AuthenticationFailureHandler verifyCodeFailureHandler = new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
                httpServletResponse.setContentType("application/json;charset=UTF-8");
@@ -104,20 +116,74 @@
            }
        };
        //处理没有权限
        private AuthenticationFailureHandler authenticationFailureHandler = new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
                httpServletResponse.setStatus(HttpStatus.FORBIDDEN.value());
            }
        };
        @Override
        protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
            if (!LOGIN_PROCESSING_URL.equalsIgnoreCase(httpServletRequest.getRequestURI())) {
                filterChain.doFilter(httpServletRequest, httpServletResponse);
                //非登录接口
                String url = httpServletRequest.getRequestURI();
                //不验证静态资源
                AntPathMatcher pathMatcher = new AntPathMatcher();
                for (String resource : STATIC_RESOURCE_PATHS) {
                    if (pathMatcher.match(resource, url)) {
                        filterChain.doFilter(httpServletRequest, httpServletResponse);
                        return;
                    }
                }
                //尚未登录授权的就不需要验证权限了
                SecurityContext contextSession = (SecurityContext) httpServletRequest.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
                if (contextSession == null) {
                    filterChain.doFilter(httpServletRequest, httpServletResponse);
                    return;
                }
                Authentication authentication = contextSession.getAuthentication();
                if (authentication == null) {
                    filterChain.doFilter(httpServletRequest, httpServletResponse);
                    return;
                }
                AdminUser adminUser = (AdminUser) authentication.getPrincipal();
                if (adminUser == null) {
                    filterChain.doFilter(httpServletRequest, httpServletResponse);
                    return;
                }
                //验证权限
                for (String path : adminUser.getRules()) {
                    if (pathMatcher.match(path, url)) {
                        //有权限
                        filterChain.doFilter(httpServletRequest, httpServletResponse);
                        return;
                    }
                }
                //无权限
                authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, null);
            } else {
                //登录接口
                try {
                    verificationCode(httpServletRequest);
                    filterChain.doFilter(httpServletRequest, httpServletResponse);
                } catch (VerificationCodeException e) {
                    authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
                    verifyCodeFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
                }
            }
        }
        /**
         * @return void
         * @author hxh
         * @description 验证验证码是否正确
         * @date 16:54 2022/5/19
         * @param: httpServletRequest
         **/
        private void verificationCode(HttpServletRequest httpServletRequest) throws VerificationCodeException {
            String requestCode = httpServletRequest.getParameter("captcha");
            HttpSession httpSession = httpServletRequest.getSession();
@@ -126,8 +192,6 @@
            if (StringUtil.isNullOrEmpty(captcha) || StringUtil.isNullOrEmpty(requestCode) || !captcha.equalsIgnoreCase(requestCode)) {
                throw new VerificationCodeException();
            }
        }
    }
@@ -181,8 +245,8 @@
                .and()
                .csrf().disable()
                .rememberMe().userDetailsService(new MyUserDetailsService())
                .and().exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint());
        http.addFilterBefore(new VerificationCodeFilter(), UsernamePasswordAuthenticationFilter.class);
                .and().exceptionHandling().authenticationEntryPoint(new NotLoginAuthenticationEntryPoint());
        http.addFilterBefore(new PreRequestVerifyFilter(), UsernamePasswordAuthenticationFilter.class);
    }
    @Override
@@ -243,12 +307,17 @@
    }
    //自定义未授权返回
    class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    /**
     * @author hxh
     * @description 未登录的事件处理
     * @date 16:55 2022/5/19
     * @return
     **/
    class NotLoginAuthenticationEntryPoint implements AuthenticationEntryPoint {
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response,
                             AuthenticationException authException) throws IOException, ServletException {
            String url = request.getRequestURI().toString();
            String url = request.getRequestURI();
            if (url.contains("/admin/api/")) {
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
            } else {
@@ -256,6 +325,5 @@
            }
        }
    }
}