Fullstack Java: Securing Your APIs with JWT Tokens in Spring Boot

Security is a fundamental requirement for any fullstack Java application, especially when APIs are exposed to the internet. One of the most effective and modern approaches to API security is using JWT (JSON Web Tokens). In this blog, we’ll walk through the concept of JWT, why it’s used, and how to implement it in a Spring Boot application to secure your backend APIs.


What is JWT?

JWT (JSON Web Token) is a compact, self-contained way to securely transmit information between parties as a JSON object. It consists of three parts:

Header – contains the signing algorithm (e.g., HS256)

Payload – includes user information and claims (e.g., username, roles)

Signature – ensures the token hasn't been tampered with

Once a user is authenticated, the server generates a JWT and sends it to the client. The client stores this token (usually in local storage or cookies) and includes it in the Authorization header for subsequent requests.


Why JWT for Spring Boot APIs?

Stateless Authentication: No need to store session data on the server

Scalability: Suitable for microservices and distributed systems

Flexibility: Can include custom claims (e.g., roles, permissions)

Security: Ensures that only authenticated users access protected APIs


Steps to Secure Spring Boot APIs with JWT

1. Add Dependencies

Use Maven or Gradle to include the necessary libraries:


xml

\

<!-- Maven -->

<dependency>

    <groupId>io.jsonwebtoken</groupId>

    <artifactId>jjwt</artifactId>

    <version>0.9.1</version>

</dependency>


2. Create a JWT Utility Class

This class will generate and validate tokens.


java


public class JwtUtil {

    private final String SECRET_KEY = "your_secret";


    public String generateToken(String username) {

        return Jwts.builder()

            .setSubject(username)

            .setIssuedAt(new Date(System.currentTimeMillis()))

            .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60)) // 1 hour

            .signWith(SignatureAlgorithm.HS256, SECRET_KEY)

            .compact();

    }


    public String extractUsername(String token) {

        return Jwts.parser().setSigningKey(SECRET_KEY)

            .parseClaimsJws(token).getBody().getSubject();

    }


    public boolean validateToken(String token, String username) {

        return extractUsername(token).equals(username) && !isTokenExpired(token);

    }


    private boolean isTokenExpired(String token) {

        return Jwts.parser().setSigningKey(SECRET_KEY)

            .parseClaimsJws(token).getBody().getExpiration().before(new Date());

    }

}


3. Configure Security Filter

Create a filter that intercepts every request and checks for JWT validity.


java


public class JwtRequestFilter extends OncePerRequestFilter {

    @Autowired

    private JwtUtil jwtUtil;


    @Override

    protected void doFilterInternal(HttpServletRequest request,

                                    HttpServletResponse response,

                                    FilterChain filterChain)

        throws ServletException, IOException {


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


        String username = null;

        String jwt = null;


        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {

            jwt = authorizationHeader.substring(7);

            username = jwtUtil.extractUsername(jwt);

        }


        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

            if (jwtUtil.validateToken(jwt, username)) {

                UsernamePasswordAuthenticationToken authToken =

                    new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());

                SecurityContextHolder.getContext().setAuthentication(authToken);

            }

        }

        filterChain.doFilter(request, response);

    }

}


4. Secure Endpoints in Spring Security Config

java


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

}

Conclusion

JWT is a powerful tool for securing APIs in a Spring Boot fullstack Java application. By implementing JWT-based authentication, you ensure stateless, scalable, and secure interactions between the frontend and backend. It’s especially beneficial in RESTful and microservice architectures where session management is impractical. With the right setup, your APIs are not only functional but fortified.


Learn FullStack Java Course in Hyderabad

Read More : Fullstack Java: Using AWS S3 for File Storage in Java Applications

Read More : Fullstack Java with Docker: Containerizing Java Applications

Read More : Introduction to Fullstack Java: Combining Backend and Frontend with Spring Boot and React

Visit Our IHUB Talent Institute Hyderabad

Comments

Popular posts from this blog

How to Use Tosca's Test Configuration Parameters

Using Hibernate ORM for Fullstack Java Data Management

Creating a Test Execution Report with Charts in Playwright