根据春季医生,它说:
返回不更改输入参数的Customizer。
但这究竟意味着什么呢?
例如,如果我像这样使用它,结果是什么:
@EnableWebSecurity
@Configuration
public class SecurityConfiguration {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeHttpRequests((authz) -> authz.anyRequest().authenticated())
.httpBasic(withDefaults());
return http.build();
}
}
发布于 2022-08-30 15:42:49
根据爪哇文档,我们有
public HttpSecurity httpBasic(Customizer<HttpBasicConfigurer<HttpSecurity>> httpBasicCustomizer) throws Exception {
httpBasicCustomizer.customize((HttpBasicConfigurer)this.getOrApply(new HttpBasicConfigurer()));
return this;
}
该参数的类型为Customizer<HttpBasicConfigurer<HttpSecurity>>
,可用作lambda函数,以传递您希望应用于提供给httpBasic
方法的配置程序中的更改。此方法还返回生成的HttpSecurity
,因此在httpBasic(....)
方法结束时已经应用了配置程序。
相对于您的示例,让我们将其命名为示例1
httpSecurity.httpBasic(httpSecurityHttpBasicConfigurer -> {
httpSecurityHttpBasicConfigurer.realmName("My Realm");
httpSecurityHttpBasicConfigurer.authenticationEntryPoint(new YourAuthEntryClass());
})
.authorizeRequests().and().csrf().disable().authorizeHttpRequests((authz) -> authz.anyRequest().authenticated());
因此,配置程序将通过您提供的lambda函数将realmName
和authenticationEntryPoint
应用于httpSecurity
。
如果您不想在httpSecurity
方法中对httpBasic
进行任何修改,那么您也可以在
httpSecurity.httpBasic(httpSecurityHttpBasicConfigurer -> {} )
.authorizeRequests().and().csrf().disable().authorizeHttpRequests((authz) -> authz.anyRequest().authenticated());
为了避免将这个非httpSecurityHttpBasicConfigurer -> {}
作为参数写入,Spring还提供了函数接口Customizer
中的静态withDefaults
方法。请记住,这个Customizer
只是一个通用接口,也将在其他地方使用,而不仅仅是在这里。
@FunctionalInterface公共接口定制器{ void ( t);静态定制器withDefaults() {返回(T) -> { };}
因此,为了避免
httpSecurity.httpBasic(httpSecurityHttpBasicConfigurer -> {} )....
你也可以写
httpSecurity.httpBasic(Customizer.withDefaults())....
这意味着不会在httpBasic
方法内应用httpSecurity
对象中的任何配置。
请记住,但是,您也可以从Java文档获得另一个方法
public HttpBasicConfigurer<HttpSecurity> httpBasic() throws Exception { return (HttpBasicConfigurer)this.getOrApply(new HttpBasicConfigurer()); }
它也可以使用,这并不返回修改过的httpSecurity
对象,而是一个HttpBasicConfigurer
,它可以编写成使用构建器模式修改httpSecurity
。
因此,示例1现在可以编写为
httpSecurity.httpBasic()
.realmName("My Realm")
.authenticationEntryPoint(new YourAuthEntryClass())
.and().authorizeRequests().and().csrf().disable()
.authorizeHttpRequests((authz) -> authz.anyRequest().authenticated());
如果您不想向httpSecurity
应用任何基本的http配置更改,您只需跳过构建器模式中的realmName
和authenticationEntryPoint
方法,它将再次为您提供httpSecurity
的默认基本配置
httpSecurity.httpBasic()
.and()
.authorizeRequests().and().csrf().disable()
.authorizeHttpRequests((authz) -> authz.anyRequest().authenticated());
的版本完全相同。
httpSecurity.httpBasic(Customizer.withDefaults())
.authorizeRequests().and().csrf().disable()
.authorizeHttpRequests((authz) -> authz.anyRequest().authenticated());
发布于 2022-08-29 13:52:40
使用默认设置。
为了前夫,
https://stackoverflow.com/questions/73529846
复制相似问题