SpringSecurity
SpringSecurity
SpringSecurity
Voici un exemple pour intégrer Spring Security dans votre projet Spring Boot. Cet
exemple implémente une authentification simple en mémoire (avec utilisateurs et
rôles) et protège vos endpoints REST.
---
---
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws
Exception {
http
.csrf().disable() // Désactiver CSRF pour simplifier les tests des APIs
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/api/public/**").permitAll() // Accessible à tous
.anyRequest().authenticated() // Authentification requise pour le
reste
)
.httpBasic(); // Utiliser HTTP Basic Authentication pour simplifier
return http.build();
}
@Bean
public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
UserDetails user = User
.withUsername("user")
.password(passwordEncoder.encode("password"))
.roles("USER")
.build();
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(); // Encodeur pour sécuriser les mots de
passe
}
}
```
---
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class DemoController {
@GetMapping("/public")
public String publicEndpoint() {
return "This is a public endpoint, accessible to everyone!";
}
@GetMapping("/user")
public String userEndpoint() {
return "This is a user-protected endpoint, accessible to authenticated
users!";
}
@GetMapping("/admin")
public String adminEndpoint() {
return "This is an admin-protected endpoint, accessible to admins only!";
}
}
```
---
### Étape 4 : Testez l'application
1. **Lancez l'application.**
2. Accédez aux endpoints avec Postman ou cURL :
- **Endpoint public** :
```bash
curl http://localhost:8080/api/public
```
Réponse : `"This is a public endpoint, accessible to everyone!"`
---