在搞 Spring Security 的時候遇到了一個小坑,就是靜態資源加載的問題。
當我們繼承了 WebSecurityConfigurerAdapter的時候,會去重寫幾個方法。去設定我們自己要過濾的路徑或者是權限的一些規則。
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
CustomUserService customUserService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserService).passwordEncoder(new BCryptPasswordEncoder());
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/global/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 開始請求權限配置
.authorizeRequests()
// 我們指定任何用戶都可以訪問多個URL的模式。
// 任何用戶都可以訪問以"/resources/","/signup", 或者 "/about"開頭的URL。
// .antMatchers("/global/**","/static/**").permitAll()
// 請求匹配 /admin/** 只擁有 ROLE_ADMIN 角色的用戶可以訪問
.antMatchers("/admin/**").hasRole("ADMIN")
// 請求匹配 /user/** 擁有 ROLE_ADMIN 和 ROLE_USER 的角色用戶都可以訪問
.antMatchers("/user/**").hasAnyRole("ADMIN", "USER")
// 任何以"/db/" 開頭的URL需要同時具有 "ROLE_ADMIN" 和 "ROLE_DBA"權限的用戶才可以訪問。
// 和上面一樣我們的 hasRole 方法也沒有使用 "ROLE_" 前綴。
// .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
// 其余所有的請求都需要認證后才可以訪問
.anyRequest().authenticated().and().formLogin()
// 登陸界面;默認登陸成功后的界面(不起作用);默認登陸失敗的界面;表單提交地址
.loginPage("/login").defaultSuccessUrl("/index.html").failureUrl("/login?error=true")
// 默認用戶名鍵值,默認密碼鍵值
.usernameParameter("username").passwordParameter("password").permitAll().and().rememberMe()
.tokenValiditySeconds(1209600).key("rememberme");
// .and()
// .logout().logoutUrl("").logoutSuccessUrl("/index.html").permitAll();
}
}
在一般來看來,我設置了
// 任何用戶都可以訪問以"/resources/","/signup", 或者 "/about"開頭的URL。
.antMatchers("/global/**","/static/**").permitAll()
或者是
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/global/**");
}
之后應該沒有什么問題,就應該可以訪問到了我們的資源。可是當你運行起demo之后,你會發現,世界並不是你想象的那個樣子。你還太年輕。
你所要的靜態資源還是加載不出來。后來發現,我們還需要去配置一下 SpringMVC 里的 addResourceHandlers
方法。
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addViewControllers(ViewControllerRegistry registry) {
// TODO Auto-generated method stub
// 注冊訪問 /login 轉向 page-login.html 頁面
registry.addViewController("/login").setViewName("page-login.html");
super.addViewControllers(registry);
}
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
// TODO Auto-generated method stub
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
super.addResourceHandlers(registry);
}
}
看起來,這次應該就可以了吧。 Run ...
可是還是太年輕。依舊沒有加載到資源。
這個,這個就有點凌亂了。。。。
過了好久好久好久,睡了一覺起來。
原來是HTML出了問題。對,沒有聽錯是 HTML 出了問題。
在加載 css 或者是 js 資源的時候,我們要寫的更加標准一些。
<link href="/global/css/style.css" rel="stylesheet" type="text/css" />
<script src="/global/js/custom.min.js" type="text/javascript"></script>
而不是
<link href="/global/css/style.css"/>
<script src="/global/js/custom.min.js"></script>