在Spring Boot Rest服务器上自定义403错误

时间:2017-05-15 13:56:05

标签: json rest spring-boot spring-security

我正在尝试(没有成功)在我的Spring启动应用程序上自定义403异常错误。 此应用程序是一个返回json响应的休息服务器。它具有自定义AuthenticationProvider,用于检查JWT令牌的有效性。当令牌过期时,我想返回自定义JSON响应而不是默认响应(即{“timestamp”:1494852457132,“status”:403,“error”:“Forbidden”,“message”:“Access”拒绝“,”路径“:”/ api / factory / application“})

以下是代码的重要部分:

安全配置类

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private JwtAuthenticationProvider jwtAuthenticationProvider;

    @Autowired
    private JwtAuthFilter jwtAuthFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("/v2/api-docs").permitAll()
                //.anyRequest().authenticated()
                .antMatchers("/application/**").authenticated()
                //@JLC:add test in security
                .antMatchers("/test/**").permitAll()
                .and()
                .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth)  throws Exception {
        auth.authenticationProvider(jwtAuthenticationProvider);
    }
}

过滤器:

@Component
public class JwtAuthFilter extends GenericFilterBean {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        String authorization = servletRequest.getHeader("Authorization");
        if (authorization != null) {
            JwtAuthToken token = new JwtAuthToken(authorization.replaceAll("Bearer ", ""));
            SecurityContextHolder.getContext().setAuthentication(token);
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}

和身份验证提供商:。这是在这个类中(在调用方法jwtService.verify期间),如果令牌过期,可能会引发异常。

@Component
public class JwtAuthenticationProvider implements AuthenticationProvider {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    private final JwtService jwtService;

    @SuppressWarnings("unused")
    public JwtAuthenticationProvider() {
        this(null);
    }

    @Autowired
    public JwtAuthenticationProvider(JwtService jwtService) {
        this.jwtService = jwtService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        log.info("authenticate ... entering" + authentication.getCredentials());
        try {
            AuthenticationInfo authentInfo = jwtService.verify((String) authentication.getCredentials());
            Authentication profile = new JwtAuthenticatedProfile(authentInfo);

            return profile;
        } catch (Exception e) {
            log.error("Error authenticate", e);
            throw new JwtAuthenticationException("Failed to verify token", e);
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return JwtAuthToken.class.equals(authentication);
    }
}

我试图在过滤器中捕获异常,但是我从未输入catch子句,我也尝试按照这篇文章中的说明Handle Security exceptions in Spring Boot Resource Server,但没有成功:当引发异常时,代码没有输入 RestAuthenticationFailureHandler 类的 onAuthenticationFailure 方法。

备注: JWT令牌已由其他服务器生成

0 个答案:

没有答案