📚 Cheatsheet

Une collection organisée de snippets de code pour accélérer votre développement. Parcourez, recherchez et copiez en un clic.

Snippets 8

Retour
Authentification avec un UserDetailsService
Avancé
@Service
public class MyUserDetailsService implements UserDetailsService {
    // ... implémentation de loadUserByUsername
}
Authentification en mémoire
Facile
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
      .withUser("user").password(passwordEncoder().encode("pass")).roles("USER");
}
Configuration CORS
Avancé
@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("http://localhost:3000");
        }
    };
}
Configuration de base (WebSecurityConfigurerAdapter)
Facile
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .anyRequest().authenticated()
            .and().formLogin();
    }
}
Configurer un encodeur de mot de passe
Facile
@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}
Dépendance 'spring-boot-starter-security'
Facile
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
Désactiver CSRF
Intermédiaire
http.csrf().disable();
Sécuriser des URL spécifiques
Intermédiaire
http.authorizeRequests()
    .antMatchers("/admin/**").hasRole("ADMIN")
    .antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
    .antMatchers("/").permitAll()