[英]Setup Spring security to redirect user to login page if not authenticated
我有一個具有 Spring 安全性的 Spring 啟動應用程序。
我的問題與此類似,但在我的情況下,如果他在嘗試訪問應用程序的任何頁面時未通過身份驗證,我想將用戶重定向到login
頁面。
下圖顯示了應用程序的架構:
我的配置類如下所示:
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/**").hasAnyRole("USER")
.and().formLogin().loginPage("/login").permitAll()
.and().authorizeRequests().antMatchers("/resources/**").permitAll().anyRequest().permitAll();
}
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
}
}
使用此配置,將不會加載任何資源。 如果用戶未通過身份驗證並且同時加載了我的資源文件夾,我該如何配置我的項目以將用戶重定向到登錄頁面?
plz結帳configure
方法
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.antMatchers("/login*").permitAll()
.anyRequest().authenticated()
.and().formLogin().loginPage("/login");
}
並implements WebMvcConfigurer
如下的implements WebMvcConfigurer
類
@Configuration
@EnableWebMvc
public class WebMvcConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
}
}
addResourceHandlers
意味着在/ static中查找資源。
當向它發出“GET”請求時,Spring Security 不允許您的 css 通過將以下行更改為下一行來允許它
這一行 = .antMatchers("/*.js").permitAll()
這一行 = .antMatchers("/*.js", "/*.css").permitAll()
使用如下所示的authenticated()
更新您的方法。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login*").
.antMatchers("/resources/**").permitAll()
.antMatchers("/*.js").permitAll()
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin();
}
請參閱這篇文章
在身份驗證之前,我在登錄頁面中遇到了這個問題,我發現它並通過在 SecurityConfig 中覆蓋此方法解決了我的問題
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/resources/**");
}
之后登錄頁面知道 .js 和 .css
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.