设置 Spring security 将用户重定向到登录页面(如果未通过身份验证)

2024-01-09

我有一个带有 Spring 安全性的 Spring boot 应用程序。

我的问题类似于this one https://stackoverflow.com/questions/25368535/when-spring-security-enabled-resoucescss-or-js-cant-be-loaded,但就我而言,我想将用户重定向到login如果他尝试访问时未通过身份验证,则显示该页面any应用程序的页面。

下图显示了该应用程序的架构:

我的配置类如下所示:

@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");
    }

}

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


请结帐configure method

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

and implements WebMvcConfigurer类如下

@Configuration
@EnableWebMvc
public class WebMvcConfiguration implements WebMvcConfigurer {

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

设置 Spring security 将用户重定向到登录页面(如果未通过身份验证) 的相关文章

随机推荐