Search code examples
javaspring-security

Migrating Spring Security 5 to Spring Security 6 HttpSecurity issue


What should be the alternative of below code in Spring Security 6?

 http
     .authorizeRequests()
         .requestMatchers("/hub/**").access("hasPermission('SOME_LAYER', '')")
         .and()
     .exceptionHandling()
         .accessDeniedHandler(accessDeniedHandlerClass)
         .and() 
     .authorizeRequests()
         .anyRequest().authenticated()
         .and()
     .sessionManagement()
         .sessionCreationPolicy(SessionCreationPolicy.NEVER);

Solution

  • in Spring Security 6 the alternative of code as below

            @Bean
            SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
                return  http
                        .authorizeHttpRequests(c->c.requestMatchers("/hub/**").access(new WebExpressionAuthorizationManager("hasPermission('SOME_LAYER', '')")).anyRequest().permitAll())
                        .exceptionHandling(c->c.accessDeniedHandler(accessDeniedHandlerClass))
                        .sessionManagement(c->c.sessionCreationPolicy(SessionCreationPolicy.NEVER))
                        .build();
            }