设置 Spring 安全性以在未通过身份验证的情况下将用户重定向到登录页面

Jor*_*oel 8 java spring spring-security spring-boot

我有一个具有 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");
    }

}
Run Code Online (Sandbox Code Playgroud)

使用此配置,将不会加载任何资源。如果用户未通过身份验证并且同时加载了我的资源文件夹,我该如何配置我的项目以将用户重定向到登录页面?

小智 5

lz结账configure方法

@Override
  public void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .antMatchers("/resources/**").permitAll()
        .antMatchers("/login*").permitAll()
        .anyRequest().authenticated()
        .and().formLogin().loginPage("/login");
  }
Run Code Online (Sandbox Code Playgroud)

implements WebMvcConfigurer类如下

@Configuration
@EnableWebMvc
public class WebMvcConfiguration implements WebMvcConfigurer {

  @Override
  public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/static/**")
        .addResourceLocations("classpath:/static/");
  }
}
Run Code Online (Sandbox Code Playgroud)

addResourceHandlers 表示在 /static 中查找资源。


Ali*_*ien 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();
        }
Run Code Online (Sandbox Code Playgroud)

参考这篇文章