Configure 403 error on spring boot server

I am trying (without success) to configure a 403 exception error in my spring boot application. This app is a rest server that returns a json response. It has a custom AuthenticationProvider that validates the validity of the JWT token. When the token has expired, I would like to return a custom JSON response, not a standard one (which is {"timestamp": 1494852457132, "status": 403, "error": "Forbidden", "message": "Access Denied", " path ":" / api / factory / application "})

Here's the important piece of code:

Security Configuration Class :

@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);
    }
}

      

Filter:

@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() {

    }
}

      

And an authentication provider: . It is in this class (during the call to the jwtService.verify method) where an exception can be thrown if the token has expired.

@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);
    }
}

      

I tried to catch the exception in the filter, but I never enter the catch clause, I also tried to follow the statement in this post Exclude security errors in spring Boot Resource Server , but no success: when an exception is thrown, no code is injected in the onAuthenticationFailure method of the RestAuthenticationFailureHandler class.

Note: The JWT token was generated by another server

+3
json rest spring-boot spring-security


source to share


No one has answered this question yet

See similar questions:

13
Handling Security Exceptions in Spring Boot Resource Server
4
Customize Authentication Failure Response in Spring Security with AuthenticationFailureHandler
1
Throwing Exception in AuthenticationProvider

or similar:

2480
How do I send JSON data using Curl from terminal / command line to Test Spring REST?
708
How to configure port for Spring Boot application
46
How to secure REST API with Spring Boot and Spring Security?
13
Security configuration with Spring-boot
ten
spring boot authentication using graphql
3
Spring boot security consider case insensitive username check for login
2
Configuring Spring Security for Safe Space
2
Spring Security OAuth2 SSO with custom provider + logout
0
Spring Security Thymleaf static resources not loading
0
Spring Cloud Upgrade fails from Edgware (Spring boot 1.x) to Greenwich (Spring boot 2.x)



All Articles
Loading...
X
Show
Funny
Dev
Pics