12 Eylül 2022 Pazartesi

SpringSecurity SecurityFilterChain Sınıfı - Yeni Component Based Approach

Giriş
Açıklaması şöyle
With Spring Security 5 a security configuration class or classes would normally inherit WebSecurityConfigurerAdapter and override the configure method.

In Spring Security 6, it is now a Bean that takes HttpSecurity object as a parameter and returns SecurityFilterChain object.
WebSecurityConfigurerAdapter sınıfından kalıtıp "configure(HttpSecurity http)" metodunu override etmek yerine, kendimiz bir SecurityFilterChain döndürüyoruz. 

Bu sınıfı oluşturturken lambda'lar ağırlıklı olarak kullanılıyor. 

SpringBoot 3 ile Gelen Farklılıklar
1. antMatchers() yerine requestMatchers() metodu kullanılıyor
Açıklaması şöyle
One change requires source modification: with Spring Security 5, we used .antMatchers method of authorizeRequest object. With Spring Security 6, it has been renamed to .requestMatchers. Otherwise, everything is as it was before, except that this method must now have a call to create SecurityFilterChain object from http parameter by calling http.build().
2. Açıklaması şöyle. Yani iki tane yıldız olmak zorunda
After switching to Spring Security 6, the previous configuration does not work any longer. In order to handle requests properly, it has to be as follows :

.requestMatchers(HttpMethod.GET,"/ws/user/**",
addFilterBefore metodu
Örnek
Şöyle yaparız
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { 
  http
    .csrf()
    .disable()

    // Add Paseto token filter
    .addFilterBefore(authTokenFilter, UsernamePasswordAuthenticationFilter.class)
    .authenticationProvider(authenticationProvider())

    // Set unauthorized requests exception handler
    .exceptionHandling()
        .authenticationEntryPoint(new HandlerAuthenticationEntryPoint())
        .accessDeniedHandler(new HandlerAccessDeniedHandler())
    .and()
      .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and()

      // Set permissions on endpoints
      .authorizeHttpRequests()
      .requestMatchers("/api/account/authenticate").permitAll()
      .requestMatchers("/api/account/register").permitAll()
      .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
      .requestMatchers(
        "/configuration/ui",
        "/swagger-resources/**",
        "/configuration/security",
        "/webjars/**").permitAll()
        .requestMatchers("/api/**").authenticated();
      
  return http.build();
}
authorizeHttpRequests  metodu
SecurityFilterChain.authorizeHttpRequests metodu yazısına taşıdım

csrf metodu
CsrfConfigurer yazısına taşıdım

cors metodu
Örnek
Şöyle yaparız
@Configuration
@EnableWebSecurity public class WebSecurityConfig { ... @Bean public SecurityFilterChain auth0FilterChain(HttpSecurity http) throws Exception { http.cors() .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .securityMatcher("/ws/**") .authorizeHttpRequests(autorizeRequests -> autorizeRequests .requestMatchers(HttpMethod.GET, "/ws/healthz", "/ws/ready", "/ws/version") .permitAll() .requestMatchers(HttpMethod.GET, "/ws/user/**","/ws/user/avatar/*","/ws/user/search") .hasAnyAuthority("SCOPE_tmt:user") .requestMatchers(HttpMethod.POST, "/ws/friend","/ws/user/trip", "/ws/trip/*") .hasAnyAuthority("SCOPE_tmt:user") ) .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt); http.csrf().disable(); http.headers().frameOptions().disable(); return http.build(); } }
Örnek
Şöyle yaparız
// Spring Boot 3.0.0
@Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  // ...
  http.authorizeHttpRequests()
    // Public endpoints
    .requestMatchers(HttpMethod.GET, "/swagger-ui.html").permitAll()
    .requestMatchers(HttpMethod.GET, "/swagger-ui/**").permitAll()
    .requestMatchers(HttpMethod.GET, "/v3/api-docs/**").permitAll()
    .requestMatchers(HttpMethod.POST, "/api/auth/login").permitAll()
    .requestMatchers(HttpMethod.POST, "/api/auth/token-refresh").permitAll()
    .anyRequest().authenticated();
    // ...
}
exceptionHandling metodu
accessDeniedHandler için ServerAccessDeniedHandler nesnesi takılır
authenticationEntryPoint hatası için ServerAuthenticationEntryPoint nesnesi takılır
Örnek
Şöyle yaparız
@Configuration
@EnableWebFluxSecurity //webflux related
@EnableReactiveMethodSecurity //webflux related
public class SecurityConfig {

  //whitlisting swagger urls
  private static final String[] AUTH_WHITELIST = {
    // -- swagger ui
    "/swagger-resources/**",
    "/configuration/ui",
    "/configuration/security",
    "/swagger-ui.html",
    "/webjars/**",
    "/v3/api-docs/**"};

  //custom auth classes for validating JWT
  @Autowired
  private AuthenticationManager authenticationManager;
    
  //custom auth classes for validating JWT
  @Autowired
  private SecurityContextRepository securityContextRepository;

  @Bean
  SecurityWebFilterChain springSecurityFilterChain(final ServerHttpSecurity http) {
     http.csrf()
       .disable()
       //Disable Sessions
       .securityContextRepository(NoOpServerSecurityContextRepository.getInstance())
       // handlers fro 401 and 403
       .exceptionHandling(exception -> exception.accessDeniedHandler(new CustomAccessDeniedHandler())
         .authenticationEntryPoint(new CustomAuthenticationEntryPoint()))
       //rest services don't have a login form
       .formLogin()
       .disable()
       //disabled basic authentication
       .httpBasic()
       .disable()
       .authorizeExchange()
       //used when connecting from browsers
       .pathMatchers(HttpMethod.OPTIONS)
       .permitAll()
       //other whitelist URL, like swagger. ensure to disable in production
       .pathMatchers(AUTH_WHITELIST)
       .permitAll()
       //your auth URL
       .pathMatchers("/auth/login")
       .permitAll()
       .and()
       //spring authentication manager
       .authenticationManager(authenticationManager)
       .securityContextRepository(securityContextRepository)
       .authorizeExchange()
       .anyExchange()
       .authenticated()
       .and();
       return http.build();
    }
}

formLogin metodu
SecurityFilterChain.formLogin metodu  metodu yazısına taşıdım

oauth2ResourceServer metodu


Hiç yorum yok:

Yorum Gönder