简体   繁体   中英

GenericFilterBean response error doesn't work for all endpoints

I have implemented a GenericFilterBean to filter jwt tokens :

    public class AuthFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

        String authHeader = httpRequest.getHeader("Authorization");
        if (authHeader != null){
            String[] authHeaderArr = authHeader.split("Bearer");
            if(authHeaderArr.length > 1 && authHeaderArr[1] != null) {
                String token = authHeaderArr[1];
                try {
                    Claims claims = Jwts.parserBuilder().setSigningKey(Constants.API_SECRET_KEY).build()
                            .parseClaimsJws(token).getBody();
                    httpRequest.setAttribute("userId", Long.parseLong(claims.get("userId").toString()));
                }catch (Exception e) {
                    httpResponse.sendError(HttpStatus.FORBIDDEN.value(), "invalid/expired token");
                }
            } else {
                httpResponse.sendError(HttpStatus.FORBIDDEN.value(),
                        "Authorization token must be Bearer[token]");
            }
        } else {
            httpResponse.sendError(HttpStatus.FORBIDDEN.value(),
                    "Authorization token must be provided");
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

The filter seems to work fine and when adding url patterns they seem to be catched successfully. The issue is that the response error if the jwt is incorrect only works on one endpoint.

The working endpoint :

队列端点(预期结果)

The other endpoints :

用户帐户端点(错误未显示)

My filter looks like that :

public class WeyApplication {

    public static void main(String[] args) {
        SpringApplication.run(WeyApplication.class, args);
    }

    @Bean
    public FilterRegistrationBean<AuthFilter> filterRegistrationBean () {
        FilterRegistrationBean<AuthFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new AuthFilter());
        registrationBean.addUrlPatterns(
                "/api/en/fleet/*",
                "/api/en/users/*",
                "/api/en/ride/*",
                "/api/en/ride-request/*"
        );
        return registrationBean;
    }
}

I don't think the problem is with the url pattern since I debugged and all the endpoints added to the registrationBean does go through the doFilter method.

Wasn't aware of that but I found out while testing that Exceptions overide the response. Adding a try catch or a Error handler fixes it.

    @GetMapping("/me/account")
    public ResponseEntity<PrivateUser> getUserDetails(HttpServletRequest request,
                                                      @PathVariable String lang) {
        Long userId = (Long) request.getAttribute("userId");
        try {
            User user = userService.getUserDetails(userId, lang);
            return new ResponseEntity<>(user.getPrivateData(), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
    }

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM