【问题标题】:How to config "Spring Security" for secure /admin URL but allow all another URL?如何为安全 /admin URL 配置“Spring Security”但允许所有其他 URL?
【发布时间】:2018-05-25 12:52:45
【问题描述】:

我正在尝试为安全路由 /admin 配置 Spring Security(仅允许 ADMIN 角色访问),但我想允许所有其他路由而不对我的配置文件中的所有路由进行硬编码。

这是我的spring安全程序配置:

  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()

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

【问题讨论】:

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


    【解决方案1】:

    你应该改变 mvcMatchers 的顺序

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

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

    【讨论】:

    • 在我更改顺序并解决了许多重定向问题后,我的所有链接都重定向到登录表单。
    猜你喜欢
    • 1970-01-01
    • 2018-11-20
    • 2016-09-14
    • 2019-08-10
    • 2021-06-19
    • 2013-03-09
    • 2018-01-03
    • 2017-11-06
    • 2016-07-22
    相关资源
    最近更新 更多