Spring Security 6 with Spring Boot 3

Spring Security 6 with Spring Boot 3

Say goodbye to Old security , Say Hi to Spring Security 6 with Spring Boot 3 . it is easier and simpler.

Spring Security is a powerful and highly customizable authentication and access-control framework. it focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements.

Spring Boot provides a spring-boot-starter-security starter that aggregates Spring Security-related dependencies. you can manually add the starter, as the following example shows:

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

When we add the spring security dependency, spring security enables the security filter chain. These filters are responsible for Spring Security. So any incoming request will go through these filters and it is here that authentication and authorization takes place.

When the username and password are submitted, the UsernamePasswordAuthenticationFilter authenticates the username and password. The UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter, so the following diagram should look pretty similar:

The magic starts Here !

All in one security config . handling cors , csrf , session managment , permitted/Authorized HttpMethods/URLs .

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http, 
                                JwtAuthFilter jwtAuthFilter, 
                          OAuthLoginSuccessHandler oAuthLoginSuccessHandler) 
throws Exception {

      http
            //how to handle anonymous users
              .anonymous(AbstractHttpConfigurer::disable)
              //cors filter to be user
              .cors(c -> c.configurationSource(corsConfigurationSource()))
              .csrf(AbstractHttpConfigurer::disable)

              .authorizeHttpRequests(requests -> requests.requestMatchers(HttpMethod.POST ,"/permitted/**" ).permitAll())
              .authorizeHttpRequests(requests -> requests.requestMatchers(HttpMethod.GET ,"/v3/api-docs/**","/swagger-ui/**","/actuator/**" ).permitAll())

              .authorizeHttpRequests(requests -> requests.requestMatchers(HttpMethod.POST,"/**" ).authenticated())
              .authorizeHttpRequests(requests -> requests.requestMatchers(HttpMethod.GET,"/**" ).authenticated())
              .authorizeHttpRequests(requests -> requests.requestMatchers(HttpMethod.DELETE,"/**" ).authenticated())
              .authorizeHttpRequests(requests -> requests.requestMatchers(HttpMethod.PUT,"/**" ).authenticated())
              .authorizeHttpRequests(requests -> requests.requestMatchers(HttpMethod.PATCH,"/**" ).authenticated())

             //any custom filter needs to injected in the chain
              .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)

               //handling exception globally
              .exceptionHandling(httpSecurityExceptionHandlingConfigurer -> 
                    httpSecurityExceptionHandlingConfigurer.authenticationEntryPoint(new 
                          HttpStatusEntryPoint(HttpStatus.FORBIDDEN)))
        

              // Disable "JSESSIONID" cookies
              .sessionManagement(conf ->  
                     conf.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

      return http.build();
   }        

For authentication provider , Multiple AuthenticationProviders are available , the example below chooses DaoAuthenticationProvider with usres in db. CustomUserDetailsService handle loadUserByUsername() that retrieves users from db to return UserDetails

@Bean
   public UserDetailsService userDetailsService(){
      return new CustomUserDetailsService();
   }

@Bean
   public AuthenticationManager authenticationManager(
              AuthenticationConfiguration      config) throws Exception {
      return config.getAuthenticationManager();
   }


   @Bean
   public AuthenticationProvider authenticationProvider() {
      DaoAuthenticationProvider daoAuthenticationProvider = 
               new    DaoAuthenticationProvider();
      daoAuthenticationProvider.setUserDetailsService(userDetailsService());
      daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
      return daoAuthenticationProvider;

   }        

Springboot oauth2login with providers like Google for example as simple as follows all is needed creating oAuthLoginSuccessHandler to handle sucess login from aourh2 provider.

   .oauth2Login(httpSecurityOAuth2LoginConfigurer ->  
             httpSecurityOAuth2LoginConfigurer.successHandler(oAuthLoginSuccessHandler))        

Don't forget to enable web secuity by adding

@EnableWebSecurity        


Rest controller can further manage roles as follows :

 @PreAuthorize("hasRole('ROLE_ADMIN')")
   public ResponseEntity<MyResponse> myAdminndpoint(){ 
     .............................
   }        

Don't forget to add method security

@EnableMethodSecurity        

Security is done!

To migrate to spring security 6 , follow https://docs.spring.io/spring-security/reference/6.0/migration/index.html


要查看或添加评论,请登录

Marwa Ali的更多文章

  • Spring Security 6 with Spring Boot 3 + KeyCloak

    Spring Security 6 with Spring Boot 3 + KeyCloak

    What is KeyCloak ? KeyCloak Open Source Identity and Access Management.It provides user federation, strong…

    1 条评论
  • Spring Security 6 with Spring Boot 3 + JWT

    Spring Security 6 with Spring Boot 3 + JWT

    In continuation to my article Spring security 6 and spring boot 3 , Next introducing JWT token. Learn Jwt token here .

  • SpringBoot batch framework

    SpringBoot batch framework

    Spring Batch is a lightweight, comprehensive batch framework designed to enable the development of robust batch…

  • Dockerizing Springboot Application

    Dockerizing Springboot Application

    Docker is a powerful tool that allows developers to package their applications into containers that can be easily…

  • Kafka Event sourcing in Event Driven Architecture

    Kafka Event sourcing in Event Driven Architecture

    What is Event Sourcing ? Event Sourcing is ensuring every change to the state of an application is captured in an event…

  • Istio addons

    Istio addons

    #devops #istio #grafana #promtheus #servicemesh Please see my previous artcile at Grafana An open source monitoring…

  • Istio service mesh

    Istio service mesh

    #devops #kubernets #istio #servicemesh What is a service mesh? Developers and operators face chanllenges with a…

  • Springboot Distributed State Machine

    Springboot Distributed State Machine

    #statemachine What is a distributed state? An application may exist in a finite number of states. when something…

  • Microservices Saga Pattern with Spring State machine

    Microservices Saga Pattern with Spring State machine

    What are sagas in microservices ? A database-per-microservice model provides many benefits for microservices…

  • SpringBoot State machine

    SpringBoot State machine

    The concept of a state machine is most likely older than any reader of this reference documentation and definitely…

社区洞察

其他会员也浏览了