首页 > 其他分享 >Spring Security without the WebSecurityConfigurerAdapter

Spring Security without the WebSecurityConfigurerAdapter

时间:2023-12-22 17:57:03浏览次数:49  
标签:http Spring AuthenticationManager WebSecurityConfigurerAdapter without user new 

 

ENGINEERING | ELEFTHERIA STEIN-KOUSATHANA | FEBRUARY 21, 2022 | ...

In Spring Security 5.7.0-M2 we deprecated the WebSecurityConfigurerAdapter, as we encourage users to move towards a component-based security configuration.

To assist with the transition to this new style of configuration, we have compiled a list of common use-cases and the suggested alternatives going forward.

In the examples below we follow best practice by using the Spring Security lambda DSL and the method HttpSecurity#authorizeHttpRequests to define our authorization rules. If you are new to the lambda DSL you can read about it in this blog post. If you would like to learn more about why we choose to use HttpSecurity#authorizeHttpRequests you can check out the reference documentation.

Configuring HttpSecurity

In Spring Security 5.4 we introduced the ability to configure HttpSecurity by creating a SecurityFilterChain bean.

Below is an example configuration using the WebSecurityConfigurerAdapter that secures all endpoints with HTTP Basic:

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((authz) -> authz
                .anyRequest().authenticated()
            )
            .httpBasic(withDefaults());
    }

}

Going forward, the recommended way of doing this is registering a SecurityFilterChain bean:

@Configuration
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((authz) -> authz
                .anyRequest().authenticated()
            )
            .httpBasic(withDefaults());
        return http.build();
    }

}

Configuring WebSecurity

In Spring Security 5.4 we also introduced the WebSecurityCustomizer.

The WebSecurityCustomizer is a callback interface that can be used to customize WebSecurity.

Below is an example configuration using the WebSecurityConfigurerAdapter that ignores requests that match /ignore1 or /ignore2:

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/ignore1", "/ignore2");
    }

}

Going forward, the recommended way of doing this is registering a WebSecurityCustomizer bean:

@Configuration
public class SecurityConfiguration {

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().antMatchers("/ignore1", "/ignore2");
    }

}

WARNING: If you are configuring WebSecurity to ignore requests, consider using permitAll via HttpSecurity#authorizeHttpRequests instead. See the configure Javadoc for additional details.

LDAP Authentication

In Spring Security 5.7 we introduced the EmbeddedLdapServerContextSourceFactoryBeanLdapBindAuthenticationManagerFactory and LdapPasswordComparisonAuthenticationManagerFactory which can be used to create an embedded LDAP Server and an AuthenticationManager that performs LDAP authentication.

Below is an example configuration using WebSecurityConfigurerAdapter the that creates an embedded LDAP server and an AuthenticationManager that performs LDAP authentication using bind authentication:

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .ldapAuthentication()
            .userDetailsContextMapper(new PersonContextMapper())
            .userDnPatterns("uid={0},ou=people")
            .contextSource()
            .port(0);
    }

}

Going forward, the recommended way of doing this is using the new LDAP classes:

@Configuration
public class SecurityConfiguration {
    @Bean
    public EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean() {
        EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean =
            EmbeddedLdapServerContextSourceFactoryBean.fromEmbeddedLdapServer();
        contextSourceFactoryBean.setPort(0);
        return contextSourceFactoryBean;
    }

    @Bean
    AuthenticationManager ldapAuthenticationManager(
            BaseLdapPathContextSource contextSource) {
        LdapBindAuthenticationManagerFactory factory = 
            new LdapBindAuthenticationManagerFactory(contextSource);
        factory.setUserDnPatterns("uid={0},ou=people");
        factory.setUserDetailsContextMapper(new PersonContextMapper());
        return factory.createAuthenticationManager();
    }
}

JDBC Authentication

Below is an example configuration using the WebSecurityConfigurerAdapter with an embedded DataSource that is initialized with the default schema and has a single user:

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.H2)
            .build();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("user")
            .password("password")
            .roles("USER")
            .build();
        auth.jdbcAuthentication()
            .withDefaultSchema()
            .dataSource(dataSource())
            .withUser(user);
    }
}

The recommended way of doing this is registering a JdbcUserDetailsManager bean:

@Configuration
public class SecurityConfiguration {
    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.H2)
            .addScript(JdbcDaoImpl.DEFAULT_USER_SCHEMA_DDL_LOCATION)
            .build();
    }

    @Bean
    public UserDetailsManager users(DataSource dataSource) {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("user")
            .password("password")
            .roles("USER")
            .build();
        JdbcUserDetailsManager users = new JdbcUserDetailsManager(dataSource);
        users.createUser(user);
        return users;
    }
}

Note: In these examples, we use the method User.withDefaultPasswordEncoder() for readability. It is not intended for production and instead we recommend hashing your passwords externally. One way to do that is to use the Spring Boot CLI as described in the reference documentation.

In-Memory Authentication

Below is an example configuration using the WebSecurityConfigurerAdapter that configures an in-memory user store with a single user:

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("user")
            .password("password")
            .roles("USER")
            .build();
        auth.inMemoryAuthentication()
            .withUser(user);
    }
}

The recommended way of doing this is registering an InMemoryUserDetailsManager bean:

@Configuration
public class SecurityConfiguration {
    @Bean
    public InMemoryUserDetailsManager userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("user")
            .password("password")
            .roles("USER")
            .build();
        return new InMemoryUserDetailsManager(user);
    }
}

Note: In these examples, we use the method User.withDefaultPasswordEncoder() for readability. It is not intended for production and instead we recommend hashing your passwords externally. One way to do that is to use the Spring Boot CLI as described in the reference documentation.

Global AuthenticationManager

To create an AuthenticationManager that is available to the entire application you can simply register the AuthenticationManager as a @Bean.

This type of configuration is shown above in the LDAP Authentication example.

Local AuthenticationManager

In Spring Security 5.6 we introduced the method HttpSecurity#authenticationManager that overrides the default AuthenticationManager for a specific SecurityFilterChain. Below is an example configuration that sets a custom AuthenticationManager as the default:

@Configuration
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((authz) -> authz
                .anyRequest().authenticated()
            )
            .httpBasic(withDefaults())
            .authenticationManager(new CustomAuthenticationManager());
        return http.build();
    }

}

Accessing the local AuthenticationManager

The local AuthenticationManager can be accessed in a custom DSL. This is actually how Spring Security internally implements methods like HttpSecurity.authorizeRequests().

public class MyCustomDsl extends AbstractHttpConfigurer<MyCustomDsl, HttpSecurity> {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
        http.addFilter(new CustomFilter(authenticationManager));
    }

    public static MyCustomDsl customDsl() {
        return new MyCustomDsl();
    }
}

The custom DSL can then be applied when building the SecurityFilterChain:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    // ...
    http.apply(customDsl());
    return http.build();
}

Getting Involved

We are excited to share these updates with you and we look forward to further enhancing Spring Security with your feedback! If you are interested in contributing, you can find us on GitHub.

https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter/

 

标签:http,Spring,AuthenticationManager,WebSecurityConfigurerAdapter,without,user,new,
From: https://www.cnblogs.com/softidea/p/17922087.html

相关文章

  • Spring三级缓存和循环依赖
    2023年12月22日17:02:18今天咪宝想买迪士尼娃娃,但是我买不起,还得加油。 SpringBean注入方式有至少3种,1.构造方法注入2.set方法注入(@Autowired)3.prototype多例bean注入 构造器注入和prototype注入的循环依赖会直接报错,set方式注入循环依赖不会报错,spring使用3级缓存来......
  • Spring AOP面向切面编程
    SpringAOP面向切面编程AOP:全称是AspectOrientedProgramming即:面向切面编程。在运行时,动态地将代码切入到类的指定方法、指定位置上的编程思想就是面向切面的编程参考文档https://docs.qq.com/pdf/DTXZtQ0FFb05paUJS源码代码测试pom.xml<?xmlversion="1.0"encod......
  • spring项目中自定义注解
    使用BeanPostProcessorBeanPostProcessor是Spring框架提供的一个接口,用于在Spring容器中对Bean进行后处理。自定义注解后,可以实现一个BeanPostProcessor实现类,在BeanPostProcessor的postProcessAfterInitialization()方法中,使用ClassPathScanningCandidateResol......
  • Spring连接线程的事务控制
    Spring连接线程的事务控制通过把线程ThreadLocal绑定数据库来连接Connection来控制事务源码实现的方式不够优雅代码实现pom.xml<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org......
  • Spring学习记录之Spring的入门程序
    Spring学习记录之Spring的入门程序前言这篇文章是我第二次学习b站老杜的spring相关课程所进行的学习记录,算是对课程内容及笔记的二次整理,以自己的理解方式进行二次记录,其中理解可能存在错误,欢迎且接受各位大佬们的批评指正;关于本笔记,只是我对于相关知识遗忘时快速查阅了解使用......
  • SpringBoot系列---【过滤器Filter和拦截器HandlerInterceptor的区别和用法】
    1.作用时机1.1过滤器过滤器(Filter)主要作用在请求到达Servlet或JSP之前,对请求进行预处理,可以对HTTP请求进行过滤、修改。过滤器是基于回调函数实现的,开发人员通过重写doFilter()方法实现过滤逻辑,其主要功能有:权限验证:检查用户是否已经登录或者是否具有相应的权限。数据压......
  • 解决分层打包后,报Could not find or load main class org.springframework.boot.loade
    解决分层打包后,报Couldnotfindorloadmainclassorg.springframework.boot.loader.JarLauncher错误发现问题升级到springboot3.2后,之前的分层打包启动后会报一下错误Error:Couldnotfindorloadmainclassorg.springframework.boot.loader.JarLauncherCausedby:......
  • Spring基于注解的CRUD
    目录Spring基于注解的CRUD代码实现测试方式一:使用Junit方式测试方式二:使用@RunWith(SpringJUnit4ClassRunner.class)注解测试Spring基于注解的CRUD源码代码实现pom.xml<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"......
  • Spring基于xml的CRUD
    目录基于xml的CRUD代码实现测试基于xml的CRUD源码使用C3P0连接池使用dbutils包中的QueryRunner类来对数据库进行操作代码实现pom.xml<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://ww......
  • Spring MVC 源码分析 - HandlerMapping 组件(二)之 HandlerInterceptor 拦截器
    HandlerMapping组件HandlerMapping组件,请求的处理器匹配器,负责为请求找到合适的 HandlerExecutionChain 处理器执行链,包含处理器(handler)和拦截器们(interceptors)handler 处理器是Object类型,可以将其理解成HandlerMethod对象(例如我们使用最多的 @RequestMapping 注解所标......