rest - 来自本机 Postman 应用程序的 Spring Security 授权请求
问题描述
我正在通过 REST API 实现它来探索/学习 Spring 安全模块。
为了测试影响,我们使用 Postman 本机应用程序作为休息客户端。
@RestController
@RequestMapping("/auth")
public class Employee {
@GetMapping("/status")
public ResponseEntity<String> getStatus()
{
ResponseEntity<String> responseEntity = new ResponseEntity<>("Resource is fetched", HttpStatus.OK);
return responseEntity;
}
}
上面是一块资源以供消费。下面是配置身份验证和授权的代码片段
@EnableWebSecurity
public class AppSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("ashish").password("{noop}admin").roles("USER")
.and().withUser("foo").password("{noop}foo").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/auth/status").hasRole("ADMIN").and()
.formLogin()
;
}
@Bean
public PasswordEncoder getPasswordEncoder()
{
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}
现在,在浏览器中尝试时,上面的授权代码工作正常 - 它使用其默认的弹簧登录页面。但是我不太明白如何通过邮递员执行/测试。
在方法 protected void configure(HttpSecurity http) 中,我尝试删除 formLogin() 它不起作用。我添加了 httpBasic - 它也没有工作。
在互联网上搜索时,我遇到了一些非常好的文章,但几乎所有文章都使用某种 UI 技术,如 angular 或 thymleaf 来展示我发现难以掌握的概念。
我指的是下面的视频教程来学习弹簧安全性。
https://www.youtube.com/watch?v=payxWrmF_0k&list=PLqq-6Pq4lTTYTEooakHchTGglSvkZAjnE&index=6&t=0s
提前致谢!阿什帕拉布
解决方案
- 通过邮递员发出
GET
请求http://localhost:8080/login
,它会返回一个 html。从响应中提取_csrf
令牌。它看起来像
<input name="_csrf" type="hidden"
value="1c470a6c-dff3-43aa-9d08-d308545dc880" />
- 执行以下 POST 请求,将令牌、用户名和密码
http://localhost:8080/login
复制为表单参数_csrf
记下
JESSIONID
Cookie
第二步的响应中的值。这就是authenticated session
.只要您将
JESSIONID
后续请求作为 cookie 发送,spring security 就会知道您是谁。Postman 会Cookie
自动将其添加到后续请求中。您可以手动将其添加为带有该 cookie 标头的标头,或更新邮递员设置以始终发送
JESSIONID
cookie
推荐阅读
- django - 将日期时间值从 Django 保存到 Postgres
- javascript - 如何在 TFS 小部件中创建持久参数
- spring-data-jpa - JPA Criteria API 规范<>中 toPredicate() 方法和 And/Or/Not/Where 之间的区别
- oracle - 如何在 ADF 中打开弹出窗口之前进行验证?
- python - IS8601 格式的 Python 记录器输出日期
- java - 如何让我的 java 程序接受命令行中给出的 excel 文件?
- ios - 如何关闭 UINavigationTransitionView 的 clipToBounds 值?
- gcc - #ifdef 适用于 Windows+MSVC,但不适用于 Cygwin64+gcc - 为什么?
- python - 一个 TKinter 控件中的多个事件
- jira - 寻找到期日(开始/结束日期)管理