Learning Paths

Spring Boot Fundamentals
75% Complete
Master the basics of Spring Boot development
Introduction to Spring Boot
Completed
REST API Development
Completed
Data Access with Spring Data JPA
Completed
Spring Security Basics
In Progress
Testing Spring Boot Applications
Not Started
Design Patterns in Java
50% Complete
Learn essential design patterns for better code architecture
Introduction to Design Patterns
Completed
Creational Patterns
Completed
Structural Patterns
In Progress
Behavioral Patterns
Not Started
Real-world Applications
Not Started
Current Lesson: Spring Security Basics
Learn how to secure your Spring Boot applications

Spring Security Basics

Lesson 4 of 5 in Spring Boot Fundamentals

Introduction to Spring Security

Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.

Key Concepts

  • Authentication: The process of establishing a principal is who they claim to be (a "principal" generally means a user, device or some other system).
  • Authorization: The process of deciding whether a principal is allowed to perform an action.
  • Principal: A user, device or system that can authenticate.
  • Granted Authority: An authority granted to a principal (e.g., roles, scopes, etc.).

Basic Configuration

To add Spring Security to your application, you need to include the Spring Security starter dependency in your project:

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

Once you add this dependency, your application will be secured with basic authentication for all endpoints. The default username is "user" and a random password is generated at startup.

Custom Security Configuration

To customize the security configuration, you can create a configuration class that extends WebSecurityConfigurerAdapter:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}