Learning Paths
Spring Boot Fundamentals
75% Complete
Master the basics of Spring Boot development
Introduction to Spring Boot
CompletedREST API Development
CompletedData Access with Spring Data JPA
CompletedSpring Security Basics
In ProgressTesting Spring Boot Applications
Not StartedDesign Patterns in Java
50% Complete
Learn essential design patterns for better code architecture
Introduction to Design Patterns
CompletedCreational Patterns
CompletedStructural Patterns
In ProgressBehavioral Patterns
Not StartedReal-world Applications
Not StartedCurrent 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();
}
}