如何为安全/管理URL配置“Spring Security”但允许所有其他URL?

时间:2017-12-11 22:22:31

标签: spring-mvc security spring-boot spring-security

我正在尝试为安全路由/管理员配置Spring Security(仅允许访问ADMIN角色)但我想允许所有其他路由没有硬编码我的配置文件中的所有路由。

这是我的春季安全计划配置:

  http.
        authorizeRequests()
            .mvcMatchers("/", "/login", "/registration", "/news/**").permitAll()
            .mvcMatchers("/admin/**").hasAuthority("ADMIN").anyRequest().authenticated()
        .and()
            .csrf().disable()
            .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error=true")
            .defaultSuccessUrl("/admin/news/")
            .usernameParameter("username")
            .passwordParameter("password")
        .and()
            .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/")
        .and()
            .exceptionHandling()
            .accessDeniedPage("/access-denied");

如何允许所有路由并仅保护/ admin路由和子项?

当我改变这行配置时

.mvcMatchers("/", "/login", "/registration", "/news/**").permitAll()

.mvcMatchers("/**").permitAll()

我的/管理员路线变得不安全,我可以在没有登录的情况下打开。 怎么办?

1 个答案:

答案 0 :(得分:-1)

你应该改变mvcMatchers的顺序

http
.authorizeRequests().mvcMatchers("/admin/**").hasAuthority("ADMIN").anyRequest()
.authenticated().mvcMatchers("/**").permitAll()

之后,如果您向“admin /〜”发送请求,则会出现登录表单 在另一种情况下,所有请求都将通过

相关问题