如果未通过身份验证,则设置Spring安全性以将用户重定向到登录页面

时间:2018-10-02 14:07:38

标签: java spring spring-boot spring-security

我有一个具有Spring安全性的Spring引导应用程序。

我的问题与this one类似,但是在我的情况下,如果他尝试访问 any 页面时未通过身份验证,我想将用户重定向到login页面的应用程序。

下图显示了应用程序的体系结构:

Architecture of the app

我的配置类如下:

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

}

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

3 个答案:

答案 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();
        }

引用this article

答案 2 :(得分:0)

Spring安全不允许在通过“ GET”请求进行更改时将CSS更改为下一行

此行= .antMatchers(“ / *。js”)。permitAll()

此行= .antMatchers(“ / *。js”,“ / *。css”)。permitAll()

相关问题