#Handle jwt exception in spring security

9 messages · Page 1 of 1 (latest)

native anvil
#

Hi! I am new to Spring Security and currently configuring it to use jwt token for Authentication/Authorization via youtube tutorial. I have implemented Jwt related service and it all going well.

I have try catch in JwtAuthFilter class to catch exception from token.
I have CustomAuthenticationEntryPoint class which implements AuthenticationEntryPoint and I have registered it in SecurityConfig class.

Everytime Jwt Exception occurs JwtAuthFilter catch exception but CustomAuthenticationEntryPoint doesn't catch it so it throws a long exception.

I want to catch jwt exception not only spring exception.
Can you please tell me what I am missing?

broken needleBOT
#

This post has been reserved for your question.

Hey @native anvil! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

native anvil
#

JwtAuthFilter

slim vineBOT
#
                    username = jwtService.extractUsername(token);
                } catch (ExpiredJwtException e) {
                    throw new BadCredentialsException("Expired jwt token", e);
                } catch (SignatureException e) {
                    throw new BadCredentialsException("Corrupted jwt token signature", e);
                } catch (MalformedJwtException e) {
                    throw new BadCredentialsException("Malformed jwt token", e);
                } catch (Exception e) {
                    throw new BadCredentialsException("Invalid jwt token", e);
                } ```

This message has been formatted automatically. You can disable this using /preferences.

native anvil
#

CustomAuthenticationEntryPoint

slim vineBOT
#
      
        Throwable cause = authException.getCause();
        
        if (cause instanceof ExpiredJwtException) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Expired jwt token");
        } else if (cause instanceof SignatureException) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Corrupted jwt token signature");
        } else if (cause instanceof MalformedJwtException) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Malformed jwt token");
        } else {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());
        }
    } ```

This message has been formatted automatically. You can disable this using /preferences.

native anvil
#

Security Config

slim vineBOT
#

@Bean ```
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception{

    httpSecurity.authorizeHttpRequests(auth -> auth
            .requestMatchers(allPermitPath).permitAll()
            .requestMatchers("/user").hasRole("USER")
            .requestMatchers("/admin").hasRole("ADMIN")
                .anyRequest().authenticated());
    httpSecurity.csrf(AbstractHttpConfigurer::disable);
    httpSecurity.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
    
    httpSecurity.authenticationProvider(authenticationProvider());
    httpSecurity.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
   
    httpSecurity.formLogin(AbstractHttpConfigurer::disable);
    
    httpSecurity.exceptionHandling(e -> {
        e.accessDeniedHandler(new CustomAccessDeniedExceptionHandler());
        e.authenticationEntryPoint(authenticationEntryPoint);
    });
    return  httpSecurity.build();
} ```

This message has been formatted automatically. You can disable this using /preferences.