SpringSecurity过滤器链中抛出自定义异常信息

最近在学习springsecurity时,发现在自定义过滤器中抛出的异常会被设置的异常处理器捕获,而异常处理器没有携带自己想要设置的异常信息。

springsecurity配置:

 http.csrf().disable().cors().and()
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                    .authorizeRequests()
                    .antMatchers("/register","/v2/api-docs", "/swagger-resources/configuration/ui",
                            "/swagger-resources", "/swagger-resources/configuration/security",
                            "/swagger-ui.html", "/webjars/**","/verifyCode/**",).permitAll()
                    .anyRequest().authenticated()
                    .and()
                    .formLogin()
                    .loginProcessingUrl("/doLogin")
                    .successHandler(successAuthenticationHandler)
                    .failureHandler(loginFailAuthenticationHandler)
                    .and()
                    .logout().logoutUrl("/doLogout")
                    .permitAll()
                    .invalidateHttpSession(true)
                    .logoutSuccessHandler(logoutSuccessAuthenticationHandler)
                    .and()            .exceptionHandling().authenticationEntryPoint(customAuthenticationEntryPoint).accessDeniedHandler(accessDeniedHandler)
                    .and()
                    .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                    .addFilterBefore(preLoginCheckCodeFilter,UsernamePasswordAuthenticationFilter.class)
                    .headers().cacheControl();

customAuthenticationEntryPoint(认证异常处理器):

@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        if (!response.isCommitted()) {
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            try (ServletOutputStream ous = response.getOutputStream()) {
                Map<String, Object> map = new HashMap<>(16);
                map.put("code", HttpStatus.SC_UNAUTHORIZED);
                map.put("success", false);
                map.put("message",e.getMessage());
                ous.write(JSON.toJSONString(map).getBytes(StandardCharsets.UTF_8));
            }
        }
    }
}

preLoginCheckCodeFilter:

 @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        if(loginUrl.equals(httpServletRequest.getRequestURI())){
            //校验图形验证码
            checkImageCode(httpServletRequest);
            String userName = httpServletRequest.getParameter("username");
            //角色状态是否正常
            SysUserBO userData = sysUserService.getUserData(userName);
            if(userData != null){
                //账号被锁定
                if(Constants.STRING_ONE.equals(userData.getUserStatus())){
                    throw new BusinessException(400,"该用户已被锁定!");
                }
                //账号停用
                if(Constants.STRING_ZERO.equals(userData.getUserStatus())){
                    throw new BusinessException(400,"该用户已停用!");
                }
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

测试时发现过滤器中的异常被异常处理器捕获时e.getMessage()的值一直是:Full authentication is required to access this resource,导致前端无法确定错误信息。

代码改进:

@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        if (!response.isCommitted()) {
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            try (ServletOutputStream ous = response.getOutputStream()) {
                Map<String, Object> map = new HashMap<>(16);
                map.put("code", HttpStatus.SC_UNAUTHORIZED);
                map.put("success", false);
                map.put("message",Optional.ofNullable(request.getAttribute("errorMessage")).orElse("请先登录").toString());
                ous.write(JSON.toJSONString(map).getBytes(StandardCharsets.UTF_8));
            }
        }
    }
}
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        if(loginUrl.equals(httpServletRequest.getRequestURI())){
            checkImageCode(httpServletRequest);
            String userName = httpServletRequest.getParameter("username");
            //角色状态是否正常
            SysUserBO userData = sysUserService.getUserData(userName);
            if(userData != null){
                //账号被锁定
                if(Constants.STRING_ONE.equals(userData.getUserStatus())){
                    httpServletRequest.setAttribute("errorMessage","该用户已被锁定!");
                    throw new BadCredentialsException("");
                }
                //账号停用
                if(Constants.STRING_ZERO.equals(userData.getUserStatus())){
                    httpServletRequest.setAttribute("errorMessage","该用户已停用!");
                    throw new BadCredentialsException("");
                }
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

当发生异常时,将异常信息保存到request请求中,CustomAuthenticationEntryPoint捕获到异常时直接从request中取异常信息就可以了。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值