In this section, we will delve into the concepts of user authentication and authorization in Spring Boot. Authentication is the process of verifying the identity of a user, while authorization determines what an authenticated user is allowed to do. We will cover the following topics:

  1. Understanding Authentication and Authorization
  2. Configuring Spring Security for Authentication
  3. Implementing User Authentication
  4. Implementing User Authorization
  5. Practical Example: Securing a REST API

  1. Understanding Authentication and Authorization

Authentication

Authentication is the process of verifying the identity of a user. It typically involves checking a username and password against a database or an external service.

Authorization

Authorization is the process of determining what an authenticated user is allowed to do. It involves checking the user's roles and permissions to see if they have access to a particular resource or action.

  1. Configuring Spring Security for Authentication

Spring Security is a powerful and highly customizable authentication and access-control framework. To use Spring Security in your Spring Boot application, you need to add the following dependency to your pom.xml:

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

  1. Implementing User Authentication

Step 1: Create a User Entity

First, create a User entity that will represent the users in your application.

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String password;
    private String role;

    // Getters and setters
}

Step 2: Create a User Repository

Next, create a UserRepository interface that extends JpaRepository.

public interface UserRepository extends JpaRepository<User, Long> {
    User findByUsername(String username);
}

Step 3: Create a UserDetailsService Implementation

Create a CustomUserDetailsService that implements UserDetailsService.

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

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

    private Collection<? extends GrantedAuthority> getAuthorities(User user) {
        return Collections.singletonList(new SimpleGrantedAuthority(user.getRole()));
    }
}

Step 4: Configure Spring Security

Create a SecurityConfig class to configure Spring Security.

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/user/**").hasRole("USER")
            .antMatchers("/public/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin().permitAll()
            .and()
            .logout().permitAll();
    }

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

  1. Implementing User Authorization

Authorization is handled by specifying access rules in the configure(HttpSecurity http) method of the SecurityConfig class. In the example above, we have defined the following rules:

  • URLs starting with /admin/ are accessible only to users with the ADMIN role.
  • URLs starting with /user/ are accessible only to users with the USER role.
  • URLs starting with /public/ are accessible to everyone.
  • All other URLs require authentication.

  1. Practical Example: Securing a REST API

Step 1: Create REST Controllers

Create a UserController and an AdminController to demonstrate secured endpoints.

@RestController
@RequestMapping("/user")
public class UserController {
    @GetMapping("/info")
    public String userInfo() {
        return "User Info";
    }
}

@RestController
@RequestMapping("/admin")
public class AdminController {
    @GetMapping("/info")
    public String adminInfo() {
        return "Admin Info";
    }
}

Step 2: Test the Application

Run the application and test the endpoints:

  • Access /public/info without authentication.
  • Access /user/info and /admin/info with appropriate roles.

Conclusion

In this section, we covered the basics of user authentication and authorization in Spring Boot. We learned how to configure Spring Security, implement user authentication, and define authorization rules. We also provided a practical example of securing a REST API. In the next section, we will explore implementing JWT authentication to further enhance the security of our application.

Spring Boot Course

Module 1: Introduction to Spring Boot

Module 2: Spring Boot Basics

Module 3: Building RESTful Web Services

Module 4: Data Access with Spring Boot

Module 5: Spring Boot Security

Module 6: Testing in Spring Boot

Module 7: Advanced Spring Boot Features

Module 8: Deploying Spring Boot Applications

Module 9: Performance and Monitoring

Module 10: Best Practices and Tips

© Copyright 2024. All rights reserved