【发布时间】:2015-03-08 06:54:45
【问题描述】:
我正在尝试保护我的 Spring Boot 应用程序 (1.21) 的一些 urlpattern 看起来我的 antMatchers("/report**").hasRole("REPORT") 被忽略了。 我改变了我的 antMatchers 的顺序,但这并没有改变。
例如如果我浏览到 localhost:9000/report/books 之类的内容,我需要登录,并且它仅适用于我的用户名密码组合,但我没有将 ROLE REPORT 设置为我的用户“user”。所以我希望我不能访问报告站点,但会显示该页面。
如何更改只有拥有角色报告的用户才能访问该网址?
EDIT1更新的源文件
Application.java
@SpringBootApplication
@EnableTransactionManagement
public class Application {
public static void main(String[] args) {
@SuppressWarnings("unused")
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
}
MvcConfig.java
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
}
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer(){
return new MyCustomizer();
}
private static class MyCustomizer implements EmbeddedServletContainerCustomizer {
@Override
public void customize(ConfigurableEmbeddedServletContainer factory) {
factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/error/404"));
factory.addErrorPages(new ErrorPage(Exception.class, "/error/exception"));
}
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/error/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("/css/**").addResourceLocations("classpath:/static/css/");
registry.addResourceHandler("/images/**").addResourceLocations("classpath:/static/images/");
registry.addResourceHandler("/js/**").addResourceLocations("classpath:/static/js/");
}
}
WebSecurityConfig.java
@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement().enableSessionUrlRewriting(false);
http
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll()
.and()
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/report**").hasRole("REPORT")
.anyRequest().fullyAuthenticated();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("user").roles("USER").and()
.withUser("admin").password("admin").roles("ADMIN");
}
}
【问题讨论】:
-
你使用过 @EnableWebMvcSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) 和 .fullyAuthenticated() 吗?你的整体配置是什么?
-
我添加了我所有的文件,并偶然通过了身份验证,但我仍然可以访问该页面
-
你有没有试过像 /main(允许所有)和 /report(只允许报告)这样拆分路径?
-
我在我的控制器中将@PreAuthorize("hasRole('ROLE_ADMIN')") 添加到我的@RequestMapping 方法中,它可以部分完成我想要的。我认为缺少的是: .and().exceptionHandling().accessDeniedPage("/403") 可能还有一个 AccessDeniedHander
标签: java spring-security spring-boot