web:framework:spring:security

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentes Révision précédente
Prochaine révision
Révision précédente
web:framework:spring:security [2023/12/05 10:35] – [Déclaration du service] jcheronweb:framework:spring:security [2025/12/15 09:18] (Version actuelle) – [Déclaration du service] jcheron
Ligne 7: Ligne 7:
 ===== Intégration ===== ===== Intégration =====
  
-Ajouter les dépendances suivantes à **pom.xml** :+Ajouter la dépendance suivante à **pom.xml** :
  
 <sxh xml;title:pom.xml> <sxh xml;title:pom.xml>
- <dependency> +<dependency> 
-     <groupId>org.springframework.security</groupId> +    <groupId>org.springframework.boot</groupId> 
-     <artifactId>spring-security-web</artifactId> +    <artifactId>spring-boot-starter-security</artifactId> 
- </dependency> +</dependency>
- +
- <dependency> +
-     <groupId>org.springframework.security</groupId> +
-     <artifactId>spring-security-test</artifactId> +
-     <scope>test</scope> +
- </dependency> +
-  +
- <dependency> +
-     <groupId>org.springframework.security</groupId> +
-     <artifactId>spring-security-config</artifactId> +
- </dependency>+
 </sxh> </sxh>
  
Ligne 50: Ligne 39:
 @Configuration @Configuration
 @EnableWebSecurity @EnableWebSecurity
-public class WebSecurityConfiguration +public class SecurityConfig 
 + 
     @Bean     @Bean
     public SecurityFilterChain configure(HttpSecurity http) throws Exception {     public SecurityFilterChain configure(HttpSecurity http) throws Exception {
         http.csrf(AbstractHttpConfigurer::disable).authorizeHttpRequests(         http.csrf(AbstractHttpConfigurer::disable).authorizeHttpRequests(
                         (req) -> req.requestMatchers(                         (req) -> req.requestMatchers(
-                                        AntPathRequestMatcher.antMatcher("/"), +                        PathPatternRequestMatcher.withDefaults().matcher("/"), 
-                                        AntPathRequestMatcher.antMatcher("/css/**"), +                         PathPatternRequestMatcher.withDefaults().matcher("/css/**"), 
-                                        AntPathRequestMatcher.antMatcher("/js/**"), +                         PathPatternRequestMatcher.withDefaults().matcher("/js/**"), 
-                                        AntPathRequestMatcher.antMatcher("/img/**"), +                         PathPatternRequestMatcher.withDefaults().matcher("/img/**"), 
-                                        AntPathRequestMatcher.antMatcher("/register/**")+                         PathPatternRequestMatcher.withDefaults().matcher("/register/**")
                                 )                                 )
                                 .permitAll()                                 .permitAll()
                                 .anyRequest()                                 .anyRequest()
                                 .authenticated()                                 .authenticated()
-                ).formLogin();+                );
         return http.build();         return http.build();
     }     }
Ligne 209: Ligne 198:
     @Bean     @Bean
     public DaoAuthenticationProvider authenticationProvider(UserDetailsService userService) {     public DaoAuthenticationProvider authenticationProvider(UserDetailsService userService) {
-        DaoAuthenticationProvider auth = new DaoAuthenticationProvider(); +        DaoAuthenticationProvider auth = new DaoAuthenticationProvider(userService);
-        auth.setUserDetailsService(userService);+
         auth.setPasswordEncoder(getPasswordEncoder());         auth.setPasswordEncoder(getPasswordEncoder());
         return auth;         return auth;
Ligne 238: Ligne 226:
 </sxh> </sxh>
  
 +=== Récupération Utilisateur connecté ===
 +Récupération de l'utilisateur connecté en tant que **ModelAttribute** pour utilisation dans les vues :
 +
 +<sxh java>
 +@ControllerAdvice
 +public class MainAdvice {
 +    @ModelAttribute("activeUser")
 +    public User activeUser(Authentication auth) {
 +        return (auth == null) ? null : (User) auth.getPrincipal();
 +    }
 +}
 +</sxh>
 ==== Login form personnalisée ==== ==== Login form personnalisée ====
  
Ligne 251: Ligne 251:
 Ajouter une route pour le **login** Ajouter une route pour le **login**
  
-<sxh kotlin:AppConfig> +<sxh java:AppConfig> 
-class AppConfig WebMvcConfigurer { +@Configuration 
-    override fun addViewControllers(registry: ViewControllerRegistry) { +public class WebConfiguration implements WebMvcConfigurer { 
-        registry.addViewController("/login").setViewName("loginForm")+    
 +    @Override 
 +    public void addViewControllers(ViewControllerRegistry registry) { 
 +     registry.addViewController("/login").setViewName("/forms/loginForm");
     }     }
 } }
Ligne 261: Ligne 264:
 Modifier la configuration dans **WebSecurityConfig** : Modifier la configuration dans **WebSecurityConfig** :
  
-<sxh kotlin;title:WebSecurityConfig>+<sxh java;title:WebSecurityConfiguration>
 @Configuration @Configuration
 @EnableWebSecurity @EnableWebSecurity
-@EnableMethodSecurity( 
-        prePostEnabled = true, proxyTargetClass = true 
-) 
 public class WebSecurityConfiguration { public class WebSecurityConfiguration {
  
Ligne 295: Ligne 295:
         http.csrf(AbstractHttpConfigurer::disable).authorizeHttpRequests(   // (1)         http.csrf(AbstractHttpConfigurer::disable).authorizeHttpRequests(   // (1)
                         (req) -> req.requestMatchers(                         (req) -> req.requestMatchers(
-                                        AntPathRequestMatcher.antMatcher("/h2-console/**"),   // (2)+                                        PathRequest.toH2Console(),   // (2)
                                         ...                                         ...
                                 )                                 )
Ligne 323: Ligne 323:
     static RoleHierarchy roleHierarchy() {     static RoleHierarchy roleHierarchy() {
         RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();         RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
-        hierarchy.setHierarchy("ROLE_ADMIN > ROLE_USER");+        hierarchy.setHierarchy("ROLE_ADMIN > ROLE_REDACTOR\n ROLE_REDACTOR > ROLE_USER");
         return hierarchy;         return hierarchy;
     }     }
Ligne 363: Ligne 363:
                                     )                                     )
                                     .permitAll();                                     .permitAll();
-                            req.requestMatchers(AntPathRequestMatcher.antMatcher("/admin/**")).hasRole("ROLE_ADMIN"); // (2)+                            req.requestMatchers(AntPathRequestMatcher.antMatcher("/admin/**")).hasRole("ADMIN"); // (2)
                             req.requestMatchers(AntPathRequestMatcher.antMatcher("/user/**")).hasAuthority("USER"); // (3)                             req.requestMatchers(AntPathRequestMatcher.antMatcher("/user/**")).hasAuthority("USER"); // (3)
                             req.requestMatchers(AntPathRequestMatcher.antMatcher("/staff/**")).hasAnyAuthority("USER", "ADMIN", "MANAGER"); // (4)                             req.requestMatchers(AntPathRequestMatcher.antMatcher("/staff/**")).hasAnyAuthority("USER", "ADMIN", "MANAGER"); // (4)
Ligne 376: Ligne 376:
 ^Méthode ^ Description ^ ^Méthode ^ Description ^
 | 1 - **permitAll** | Pas de sécurisation sur les urls commençant par **/css**, **/assets**, **/login**. | | 1 - **permitAll** | Pas de sécurisation sur les urls commençant par **/css**, **/assets**, **/login**. |
-| 2 - **hasRole** | Les utilisateurs ayant le rôle **ROLE_ADMIN** peuvent accéder aux urls commençant par **/admin**. |+| 2 - **hasRole** | Les utilisateurs ayant le rôle **ADMIN** peuvent accéder aux urls commençant par **/admin**. |
 | 3 - **hasAuthority** | Les utilisateurs ayant l'authority **USER** peuvent accéder aux urls commençant par **/user**. | | 3 - **hasAuthority** | Les utilisateurs ayant l'authority **USER** peuvent accéder aux urls commençant par **/user**. |
 | 4 - **hasAnyAuthority** | Les utilisateurs ayant l'une des authorities **USER**, **ADMIN** ou **MANAGER** peuvent accéder aux urls commençant par **/staff**. | | 4 - **hasAnyAuthority** | Les utilisateurs ayant l'une des authorities **USER**, **ADMIN** ou **MANAGER** peuvent accéder aux urls commençant par **/staff**. |
Ligne 473: Ligne 473:
 La protection csrf est activée par défaut dans **Spring security** La protection csrf est activée par défaut dans **Spring security**
 </wrap> </wrap>
 +
 +Mettre éventuellement une exception pour la console H2 (mais la console H2 n'a aucune raison d'être activée en production) :
 +
 +<sxh java;gutter:false>
 +req.csrf(csrf->csrf.ignoringRequestMatchers(toH2Console()))
 +</sxh>
  
 === Intégration dans les vues === === Intégration dans les vues ===
Ligne 494: Ligne 500:
 </form> </form>
 </sxh> </sxh>
 +
 +
 +<wrap important>Attention à la route **/logout**, elle devra être accédée uniquement via un POST, qui devra inclure le token CSRF.</wrap>
  
  
  • web/framework/spring/security.1701768951.txt.gz
  • Dernière modification : il y a 2 ans
  • de jcheron