Mastering Spring Security and JWT in Spring Boot

Week-05

As we conclude this incredible journey of learning Spring Boot, Week 5 brought us to the critical topic of Spring Security and JWT (JSON Web Tokens). Security is an essential aspect of any application, and this week’s lessons were all about implementing authentication, authorization, and secure user access in a Spring Boot application.

In this final blog, I’ll walk you through the concepts covered, practical implementations, and a real-world example to tie everything together.


Topics Covered

  1. Spring Security 6: Getting Started

  2. Custom Login Implementation

  3. Understanding and Using CSRF Tokens

  4. Customizing Spring Security Configurations

  5. Verifying Users from a Database

  6. Encoding Passwords with BCrypt

  7. What is JWT and Why It’s Needed

  8. Generating JWT Tokens in Spring Boot

  9. Validating JWT Tokens and Using OAuth2 for Google and GitHub Logins


1. Spring Security 6: Getting Started

What It Is:
Spring Security is a powerful framework for securing Java applications. It provides tools to handle authentication (who can access the app) and authorization (what resources users can access).

In Spring Boot, Spring Security is added via dependencies and enabled by default.

Key Concepts:

  • Secure endpoints with minimal configuration.

  • Provide login forms and default security settings.

Example:
Adding Spring Security dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2. Custom Login Implementation

What It Is:
Custom login pages allow you to replace the default Spring Security login form with your own design and functionality.

Steps:

  1. Create an HTML login page.

  2. Configure Spring Security to use this page.

Example:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.formLogin()
        .loginPage("/custom-login")
        .permitAll();
}

3. Understanding and Using CSRF Tokens

What It Is:
Cross-Site Request Forgery (CSRF) tokens prevent unauthorized commands from being performed on behalf of an authenticated user.

Spring Security automatically generates CSRF tokens and includes them in forms.

Example:
Include the token in your HTML form:

<input type="hidden" name="_csrf" value="${_csrf.token}" />

4. Customizing Spring Security Configurations

What It Is:
You can customize how Spring Security handles authentication and authorization by overriding its default behavior.

Example:

  • Permit access to public endpoints.

  • Restrict access to specific roles.

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/public/**").permitAll()
        .antMatchers("/admin/**").hasRole("ADMIN")
        .anyRequest().authenticated();
}

5. Verifying Users from a Database

What It Is:
Instead of using in-memory users, you can authenticate users directly from a database.

Steps:

  1. Store user details (username, password, roles) in a database.

  2. Configure Spring Security to fetch users from the database using UserDetailsService.

Example:

@Service
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("User not found"));
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(), user.getPassword(), user.getRoles());
    }
}

6. Encoding Passwords with BCrypt

What It Is:
Passwords should always be stored securely. BCrypt is a hashing algorithm supported by Spring Security for encrypting passwords.

Example:

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

When saving a new user:

user.setPassword(passwordEncoder.encode(plainPassword));

7. What is JWT and Why It’s Needed

What It Is:
JWT (JSON Web Token) is a compact, self-contained token for securely transmitting information between parties. It’s widely used for stateless authentication.

Why JWT:

  • Eliminates the need to store sessions.

  • Includes all necessary user information.


8. Generating JWT Tokens in Spring Boot

What It Is:
JWTs are generated during login and sent to the client. The client includes the token in subsequent requests for authentication.

Example:

String token = Jwts.builder()
        .setSubject(user.getUsername())
        .signWith(SignatureAlgorithm.HS512, "secret_key")
        .compact();

9. Validating JWT Tokens and Using OAuth2

What It Is:

  • Token Validation: Ensures the token is valid and not tampered with.

  • OAuth2 Login: Allows users to log in via third-party providers like Google or GitHub.

Example of OAuth2 Login:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.oauth2Login()
        .loginPage("/oauth2/authorization/google");
}

Real-World Example: Secure REST API with JWT

Let’s build a secure REST API for managing tasks, combining all these concepts.

  1. Endpoints:

    • POST /login: Authenticate and generate JWT.

    • GET /tasks: Fetch tasks (secured with JWT).

  2. Security:

    • Passwords are hashed with BCrypt.

    • JWT is validated before allowing access.

  3. OAuth2 Login:

    • Users can log in via Google or GitHub.

References

  1. Spring Framework Documentation

  2. Spring Boot Documentation

  3. Spring Boot and Security Tutorial Playlist by Navin Sir


Wrapping Up

This week’s focus on Spring Security and JWT marks the conclusion of our Spring Boot learning journey. From understanding the basics of Spring Framework to building secure, full-stack applications, this journey has been transformative.

Key Takeaways from the Course:

  • Spring Boot simplifies building enterprise-grade Java applications.

  • Full-stack development with React and Spring Boot offers immense flexibility and scalability.

  • Security is non-negotiable—implementing authentication and authorization with Spring Security is critical.

  • JWT provides a stateless way to secure APIs, making them robust and scalable.

I’m immensely grateful for the knowledge gained during this course and look forward to applying these skills in real-world projects. 🚀

Stay tuned for more learning adventures ahead! 💡

LinkedIn- LinkedIn Post

GitHub- Codebase

Happy coding !!😊