java - 使用 Spring Security 进行 REST API 授权
问题描述
我正在尝试使用@PreAuthorize("hasAnyRole('ADMIN')")
为此目的保护我的 API,我已经实现了UserDetailsService
从数据库中获取数据的方法。如果您尝试访问任何受保护的 API,它会向您显示默认登录表单。
我遵循的代码是这个https://github.com/TechPrimers/spring-security-example
我的项目正在成功运行。但是当我尝试在浏览器中访问我的安全 API 时,它没有显示登录表单。
此外,我希望能够在有和没有授权标头的情况下访问 REST API。
本文档
https://howtodoinjava.com/spring-boot2/security-rest-basic-auth-example/
使用InMemoryAuthentication
,它还能够使用浏览器和 Postman 访问 API。同时,我正在从我的数据库中获取数据。如何以这种方式自定义我的实现,以便它可以同时适用于浏览器和 Postman?
解决方案
下面的代码需要一个表单来匹配通配符。antMatcher 中需要开头的斜线
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/**/secured/**")
.authenticated()
.and()
.httpBasic();
}
推荐阅读
- git - 为什么带有 push 的 git 别名不起作用?
- python - AWS lambda update_thing_shadow 规则问题
- vba - Excel VBA:停止一段代码(正确)
- matlab - MATLAB - 如何梳理()单元格?
- c++ - 在 C++ 中,如何在头文件中声明一个数据结构,而它是在源文件中定义的?
- javascript - React 路由器 4 为所有路由渲染相同的组件
- cuda - 如何跨内核调用将数据保存在快速 GPU 内存(l1/共享)中?
- gradle - 使用 Kotlin 版本 1.2+,但仍然收到有关 `use` 的编译器错误
- javascript - 我画布上的正方形出现了一秒钟然后消失了
- sql - 在删除客户上创建一个触发器,显示一条消息“客户编号 217 已删除”