spring - 如何在 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()
,那么它可以正常工作。
我哪里错了?
解决方案
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")
推荐阅读
- excel - 如何根据其他代码运行 Excel VBA SendKeys
- javascript - 即使我已经安装了 Web3,也会收到消息“找不到模块 'web3'”
- java - Spring Security 自定义标头请求匹配器不起作用
- r - 如何保存具有多个几何形状的简单特征?
- python - 如果字典中已经存在键,如何向它添加多个值(Python)
- docker - Docker 容器未在 docker stack deploy 覆盖上缩减(docker-ce 20.10.0)
- java - 为什么不能将 osgi 引用声明为静态数据类型?
- svg - 将 SVG 文件转换为 Autodesk Viewer svf 格式
- sql - DBT 是 SQL 管道的正确选择吗?
- react-native - 试图在本机反应中注册两个具有相同名称的 RNCWebview ERROR 视图