Java 如何解决Spring安全性无需登录即可访问url
您好,我创建了一个示例spring mvc安全应用程序。我遵循基于java代码的配置,而不是xml配置。该应用程序运行良好。 但是,用户无需登录应用程序即可访问每个url。我如何解决这个问题 我想,用户在没有登录过程中不能访问urlJava 如何解决Spring安全性无需登录即可访问url,java,spring,spring-mvc,spring-security,Java,Spring,Spring Mvc,Spring Security,您好,我创建了一个示例spring mvc安全应用程序。我遵循基于java代码的配置,而不是xml配置。该应用程序运行良好。 但是,用户无需登录应用程序即可访问每个url。我如何解决这个问题 我想,用户在没有登录过程中不能访问url @EnableWebSecurity @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private C
@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)。因此,解决方案是删除/**
规则或使其不那么通用,这取决于您希望它做什么
顺便说一句,您应该真正遵循,这将使您的配置更易于阅读。首先包括
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("password").roles("ADMIN"); // admin in your case
}
正如@Bohuslav Burghardt建议的那样
http
.authorizeRequests()
.antMatchers("/resources/**", "/login").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/admin/home")
.failureUrl("/loginfailed")
.permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.deleteCookies("JSESSIONID")
.invalidateHttpSession( true )
.and();
您可以使用
Spring
Filter
:thnx来获得支持。但是我的项目基于Spring boot,这意味着不存在web.xml文件。我为您检查了一些自定义更改。。如果仍然不起作用,那么还有其他问题。它起作用了。我还想处理注销问题。乐:-注销后,我可以回到主页。在主页上,我也可以点击后退按钮进入登录页面。