gpt4 book ai didi

java - Spring Security protected void configure(HttpSecurity http) 请解释 "and() "的正确使用。这是什么意思?

转载 作者:行者123 更新时间:2023-12-04 15:21:29 26 4
gpt4 key购买 nike

我在这个平台和其他平台的许多搜索结果中有很多很多例子,但我找不到对“and() ”的解释。显然是某种分隔符。可能执行逻辑与 (&&),但也可能不执行。

我想了解正确的用法以及它的作用...它的含义。

我希望这个问题很突出并且答案对其他人有用

引用:https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurerAdapter.html#configure-org.springframework.security.config.annotation.web.builders.HttpSecurity-

然后在那个文档里面:

protected void configure(HttpSecurity http)
throws java.lang.Exception

覆盖此方法以配置 HttpSecurity。通常,子类不应通过调用 super 来调用此方法,因为它可能会覆盖其配置。默认配置是:

http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();

最佳答案

  • 让我们来看下面的例子。两者是等价的。
    @Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated();

http.formLogin()
.loginPage("/login")
.permitAll();

http.logout()
.permitAll();
}
     protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
  • 实际上我们在这里配置了不同的配置器,例如本例中的 ExpressionUrlAuthorizationConfigurerFormLoginConfigurerLogoutConfigurer。尽管它们在第一个中是单独配置的,但它们都是一起应用的。所以这里 AND 扮演逻辑 AND 的角色

  • 现在注意,例如,.anyRequest().authenticated() 的返回类型是 ExpressionInterceptUrlRegistry,但是方法 formLogin() 只存在于 HttpSecurity 类型的对象中,因此在构建器模式 and() 扮演第二个角色切换返回类型,即一旦你调用 anyRequest().authenticated().and(),返回类型是 HttpSecurity 所以现在它允许你开始 formLogin()

  • 请参阅 Intellij 显示不同点的返回类型。

    enter image description here

关于java - Spring Security protected void configure(HttpSecurity http) 请解释 "and() "的正确使用。这是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63193202/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com