我有一个具有Spring安全性的Spring引导应用程序。
我的问题与this one类似,但是在我的情况下,如果他尝试访问 any 页面时未通过身份验证,我想将用户重定向到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");
}
}
使用此配置,将不会加载任何资源。 如果用户未同时和通过身份验证并加载了我的资源文件夹,该如何配置我的项目以将用户重定向到登录页面?
答案 0 :(得分:2)
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
类,如下所示
@Configuration
@EnableWebMvc
public class WebMvcConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
}
}
addResourceHandlers
表示在/ static中查找资源。
答案 1 :(得分:0)
使用authenticated()
来更新您的方法,如下所示。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login*").
.antMatchers("/resources/**").permitAll()
.antMatchers("/*.js").permitAll()
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin();
}
答案 2 :(得分:0)
Spring安全不允许在通过“ GET”请求进行更改时将CSS更改为下一行
此行= .antMatchers(“ / *。js”)。permitAll()
此行= .antMatchers(“ / *。js”,“ / *。css”)。permitAll()