我正在尝试获取Spring安全性,以允许无需先登录即可提供.css .js等静态文件。
我尝试使用资源处理程序创建MVC配置,并在spring安全配置中更改规则,但是似乎没有任何效果。
MvcConfig.java:
@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/assets/**")
.addResourceLocations("/assets/");
}
}
SecurityConfig.java:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/assets/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/assets/**");
}
}
当我转到http://localhost:8080/assets/js/particles.min.js时,我希望它返回文件内容,但是每次我尝试使用localhost:8080 / assets / *之类的链接时,它都会返回login.html的内容
答案 0 :(得分:1)
假设您的静态文件位于select ( sum( class_cd in ('C2', 'C3', 'C4', 'C5') ) /
sum( class_cd in ('RX', 'OT') )
) as ratio
from t;
下:
需要配置两个主要部分:
实施src/main/resources
界面以发现您的静态资源:
WebMvcConfigurer
设置安全性配置,以允许静态资源(例如CSS,JavaScript和图像)可以公开访问:
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!registry.hasMappingForPattern("/assets/**")) {
registry.addResourceHandler("/assets/**")
.addResourceLocations("/assets/");
}
}
}
假设您有一个CSS文件,如下所示:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
// Your settings
@Override
protected void configure(HttpSecurity http) throws Exception {
// Your AuthN handlers and filter chain...
http
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/css/**").permitAll()
.antMatchers("/img/**").permitAll()
.antMatchers("/js/**").permitAll()
.anyRequest().authenticated();
// Logout handler...
}
}
Web服务器将使其在以下位置可访问:
src/main/resources/assets/css/layout.css
答案 1 :(得分:0)
尝试更改为:
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/assets/").permitAll()
.and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
答案 2 :(得分:-1)
web.ignoring().antMatchers("/assets/**");
上面的语句将告诉Spring Security忽略任何以“ / assets /” 开头的请求。因此,如果我是您,我将删除所有以下配置:
.antMatchers("/", "/assets/**")
.permitAll()
使用configure(HttpSecurity http)
方法。