首页 > 解决方案 > 在 Spring Security 配置中,所有人都允许的 Url 不可访问并重定向到登录

问题描述

在下面的配置中,我认为我没有做错任何事情。我允许所有人的 URL 将我重定向到登录页面。具有角色 USER 的用户也存在同样的问题。

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/**").hasRole("ADMIN")
                .antMatchers("/new/**", "/edit/**", "/create/**", "/save/**").hasAnyRole("USER", "ADMIN")
                .antMatchers("/", "/registration/**", "/view/**",).permitAll()
                
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login").permitAll()
                .defaultSuccessUrl("/")
                .and()
                .logout().invalidateHttpSession(true)
                .clearAuthentication(true)
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/loggingOut").permitAll();
    }

如果您可以提供任何有助于更好理解的资源。我是春天的新手,任何帮助将不胜感激。

标签: javaspringspring-security

解决方案


我认为问题出在您的角色层次结构上。试试这个。

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/new/**", "/edit/**", "/create/**", "/save/**").hasAnyRole("USER", "ADMIN")
            .antMatchers("/", "/registration/**", "/view/**",).permitAll()
            .antMatchers("/**").hasRole("ADMIN")
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login").permitAll()
            .defaultSuccessUrl("/")
            .and()
            .logout().invalidateHttpSession(true)
            .clearAuthentication(true)
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .logoutSuccessUrl("/loggingOut").permitAll();
}

如果这不起作用,请尝试不同的组合。这篇文章解释了角色层次结构,它可以帮助你。


推荐阅读