gpt4 book ai didi

java - 如何解决Spring Security无需登录即可访问url的问题

转载 作者:行者123 更新时间:2023-11-30 03:30:24 25 4
gpt4 key购买 nike

您好,我创建了一个示例 spring mvc 安全应用程序。我遵循基于 java 代码的配置而不是 xml 配置。该应用程序工作正常。但是,用户无需登录应用程序即可访问每个网址。我该如何解决这个问题?

我想,用户不能在没有登录过程的情况下访问url。

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private CustomUserDetailsService customUserDetailsService;

@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.headers()
.addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN)).and()
.formLogin().defaultSuccessUrl("/admin/home")
.loginPage("/login").failureUrl("/login?error")
.permitAll().and().logout()
.logoutSuccessUrl("/login?logout").logoutUrl("/logout")
.permitAll().and().authorizeRequests().antMatchers("/**")
.permitAll().anyRequest().authenticated().and();
}

/*
* @Override protected void configure(AuthenticationManagerBuilder auth)
* throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(customUserDetailsService);
}

}

最佳答案

我认为这就是问题所在:

.authorizeRequests()
.antMatchers("/**").permitAll()
.anyRequest().authenticated()

规则的顺序很重要(应该是最具体的在前,最不具体的在最后),因此 /** 模式将匹配所有内容以及 anyRequest().authenticated() 永远不会生效(因此将允许所有人访问所有 URL)。因此,解决方案是删除 /** 规则或使其不那么通用,具体取决于您希望它执行的操作。

顺便说一句,你真的应该遵循recommended conventions for indenting Spring Security Java configuration ,这将使您的配置更易于阅读。

关于java - 如何解决Spring Security无需登录即可访问url的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29181333/

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