September 30, 2025
JWT Authentication in Spring Boot

JWT(JSON Web Token) With SpringBoot – Step by Step Tutorial – Part 2

In Part 1, we were able to setup a Spring Boot application to use JWT. We also wrote to code to generate the JSON Web Token(JWT). In this part, you will learn how to do authorization using the JWT.

Basics

The generated token would have to be added to subsequent requests. Then spring security would be configured to intercept incoming requests, checking for JWT in the header. If it finds JWT, it does the following;

  • intercept every request and extract the JWT
  • validate the JWT
  • set the JWT in the execution context

As usual, we would follow the step by step.

Step 1 – Create Filter and implement the filter method. This is a way to intercept a request. So create filter class that extends OncePerRequestFilter. I call this class JwtRequestFilter.

Autowire the MyUserDetails service and the JwtUtility into this class

Then override the doFilterInternal() method.

Annotate the class with @Component mapping.

Extract the authorization header using request.getHeader() passing in the string “Authorization”

Initialize the username and jwtToken variables

Check if the authorizationHeader is not null and starts with “Bearer ” and extract the jwtToken and username

Next, check if the username is not null and SecurityContext is null ie authentication has not occurred. If so, then extract the userDetails, validate it using the validateToken method of the JwtUtility. If it validated, then create a new authentication token. Then using this token, set the the security context.

At the end, you then call chain.doFilter() passing in the request and response.

The complete doInternalFilter() method is given below:

@Override
protected void doFilterInternal(HttpServletRequest request,
                                HttpServletResponse response,
                                FilterChain filterChain) throws ServletException, IOException {

    final String authorizationHeader = request.getHeader("Authorization");

    String username = null;
    String jwtToken = null;

    if(authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
        jwtToken = authorizationHeader.substring(7);
        username = jwtUtility.getUsernameFromToken(jwtToken);
    }

    if(username != null && SecurityContextHolder.getContext().getAuthentication() == null){
        UserDetails userDetails = this.myUserDetailsService.loadUserByUsername(username);
        if(jwtUtility.validateToken(jwtToken, userDetails)){
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities()
            );
            usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        }
    }
    filterChain.doFilter(request, response);
}

 

Step 2 – Tell the SecurityConfigurer to use the filter chain and also make session management policy to be stateless.  You need to go to the SecurityConfigurer class and modify the configure method like so

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/authenticate").permitAll()
            .anyRequest().authenticated()
            .and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}

Notice two things from the above code:

  • session managment have been added
  • our jwtRequestFilter have been added using addFilterBefore

Finally, we are done!

You can now fire up the application and test it using postman. First do a request to /authenticate. Then use the returned token to make a request to the “/” route and all is fine.

I recommend you watch the video on my YouTube Channel.

1 1 vote
Article Rating
Subscribe
Notify of
guest

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Basu
Basu
4 years ago

Nice page for basic understanding JWT and session management.
Thanks @kindson.

Tania
Tania
3 years ago

Hi, I did all steps as you said them. But the finally exam at the POstman I have 403 error. I change the method but I am still seeing the forbiden error.