Java

Spring Security Basics

Secure your Spring Boot applications with authentication and authorization.

By TechCoder TeamLast updated: 2026-06-02
In a Nutshell

Secure your Spring Boot applications with authentication and authorization. This hands-on tutorial focuses on practical implementation of spring security basics concepts.

Spring Security Basics

Spring Security provides authentication and authorization for Spring applications.

Adding Spring Security

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

Once added, all endpoints are secured by default!

Basic Authentication

In-Memory Users

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
            )
            .httpBasic();
        return http.build();
    }
    
    @Bean
    public UserDetailsService users() {
        UserDetails user = User.builder()
            .username("user")
            .password("{noop}password") // {noop} = no encoding
            .roles("USER")
            .build();
        return new InMemoryUserDetailsManager(user);
    }
}

Role-Based Access Control

http.authorizeHttpRequests(auth -> auth
    .requestMatchers("/admin/**").hasRole("ADMIN")
    .requestMatchers("/user/**").hasAnyRole("USER", "ADMIN")
    .requestMatchers("/public/**").permitAll()
    .anyRequest().authenticated()
);

Password Encoding

Never store plain-text passwords!

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

// Usage
UserDetails user = User.builder()
    .username("admin")
    .password(passwordEncoder().encode("secret"))
    .roles("ADMIN")
    .build();

JWT (JSON Web Tokens)

For stateless authentication in REST APIs.

// Generate token
String token = Jwts.builder()
    .setSubject(username)
    .setIssuedAt(new Date())
    .setExpiration(new Date(System.currentTimeMillis() + 86400000))
    .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
    .compact();
JAVA PLAYGROUND
⏳ Loading editor…

AI Mentor

Confused about "Spring Security authentication and authorization basics"? Ask our AI mentor for a simplified explanation.

Quiz

Quiz

Question 1 of 3

What happens when you add Spring Security dependency?

Nothing changes
All endpoints are secured
App won't start