java - Spring Security 阻止非授权请求的 CSS 资源
问题描述
我正在使用 spring boot,我的 CSS 资源位于 .../src/main/resources/static 并且我有 WebSecurityConfig 类:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/registration", "/static/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService)
.passwordEncoder(NoOpPasswordEncoder.getInstance());
}
}
和 MvcConfig 类:
@Configuration
public class MvcConfig implements WebMvcConfigurer {
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
}
}
当我登录 css 资源被激活。当我没有登录时,我可以访问我的模板。
为什么 CSS 资源会阻止非授权请求?
对不起我的英语不好。我将非常感谢您的帮助!
解决方案
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/control").hasRole("ADMIN")
.antMatchers("/register", "/login_auth", "/login").permitAll()
.antMatchers("/img/*.jpg", "/*.js", "/*.css").permitAll()...
我这样做是为了访问根静态文件夹中的文件。如果您将 em 放在文件夹下,请改为:
.antMatchers("/img/**", "/js/**", "/css/**").permitAll()
推荐阅读
- java - 使用 Spring Boot 2 CXF Web 服务访问用户原理
- javascript - 如何进行递归 Promise 调用以作为 Javascript 中减少的返回?
- xaml - 在 Xamarin ListView 中呈现 ListViewItem 时出现问题
- docker - 如何修复 Docker sh 入口点中的“权限被拒绝”
- html - 图标不显示在按钮离子上
- java - 如何以编程方式从android应用程序的文件和文件夹中删除世界读/写权限?
- ios - iOS Firestore 可以将 `FieldValue.increment` 用于 Map 值吗?
- javascript - Google Places API 上的 CORS 错误,但 Reddit 上没有
- python - Pyperclip 模块在 Android 上失败
- java - 如何知道背包问题(DP实现)中选择了哪个项目?