ali-bouali / spring-boot-3-jwt-security

Sample project on how to implement JWT security based using Spring boot 3 and Spring security 6
https://aliboucoding.com/p/securing-your-spring-boot-3-0-applications-with-json-web-tokens-jwt
Apache License 2.0
1.86k stars 870 forks source link

Factory method 'securityFilterChain' threw exception with message #10

Closed SukeshU closed 1 year ago

SukeshU commented 1 year ago

When I try to start the application, I am getting this issue. Can you please help me?

Error: - Factory method 'securityFilterChain' threw exception with message: Cannot invoke "Object.getClass()" because "filter" is null

@Component @RequiredArgsConstructor public class JwtAuthenticationFilter extends OncePerRequestFilter {

private final JwtService jwtService = null; private final UserDetailsService userDetailsService = null;

@Override protected void doFilterInternal( @NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain ) throws ServletException, IOException { final String authHeader = request.getHeader("Authorization"); final String jwt; final String userEmail; if (authHeader == null ||!authHeader.startsWith("Bearer ")) { filterChain.doFilter(request, response); return; } jwt = authHeader.substring(7); userEmail = jwtService.extractUsername(jwt); if (userEmail != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = this.userDetailsService.loadUserByUsername(userEmail); if (jwtService.isTokenValid(jwt, userDetails)) { UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities() ); authToken.setDetails( new WebAuthenticationDetailsSource().buildDetails(request) ); SecurityContextHolder.getContext().setAuthentication(authToken); } } filterChain.doFilter(request, response); } }

SukeshU commented 1 year ago

I got the solution. The issue was I initialized the final keyword as "=null", which is not required.