首页 > 解决方案 > 如何在 Spring Boot 中应用基于 URL 和角色的身份验证?

问题描述

我正在尝试通过以下方式应用 URl 和基于角色的身份验证

http
    .authorizeRequests()
        .antMatchers("/rest/**").hasRole("ADMIN")
        .and()
    .authorizeRequests()
        .antMatchers("/admin/**").hasRole("MANAGER")
        .and()
    .authorizeRequests()
        .antMatchers("/restApi/**").hasRole("USER")
        .anyRequest().authenticated()
        .and()
    .formLogin()
        .permitAll();

但是在输入用户名和密码后,我回到了 Spring Boot 提供的默认登录屏幕。

如果我使用permitAll()而不是hasRole(),那么它可以正常工作。
我哪里错了?

标签: springspring-bootspring-mvcspring-security

解决方案


dur 在这里回答了使用多个休息端点的好方法:https ://stackoverflow.com/a/41527591/2566098

我用一个新项目测试了这个例子,必须在密码字符串前面添加“{noop}”才能让它工作,但效果很好。

基本上,我们将每个端点分成自己的 WebSecurityConfigurerAdapter 扩展。

在这个例子中是:

http
    .antMatcher("/api/**")
    .authorizeRequests()
    .anyRequest().hasRole("ADMIN")
    .and().httpBasic();

当您将其反转并使用 antmatchers 复数并且缺少 anyRequest() 时(不确定这是否有所不同):

http
    .authorizeRequests()
    .antMatchers("/rest/**").hasRole("ADMIN")

推荐阅读