【问题标题】:How to apply URL and role based authentication in Spring Boot?如何在 Spring Boot 中应用基于 URL 和角色的身份验证?
【发布时间】:2021-06-18 10:42:49
【问题描述】:

我正在尝试通过以下方式应用 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(),那么它可以正常工作。
我哪里错了?

【问题讨论】:

  • 最后permitAll()有什么意义?
  • 你叫什么网址?
  • 您在哪里将角色应用到您的用户?

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-08-03
    • 2021-03-05
    • 2016-01-03
    • 1970-01-01
    • 2021-03-31
    • 2020-07-08
    • 1970-01-01
    • 2014-04-04
    • 2015-05-17
    相关资源
    最近更新 更多