首页 > 解决方案 > 来自本机 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 - 它也没有工作。

在邮递员中,我使用基本身份验证。 Postman 错误截图

在互联网上搜索时,我遇到了一些非常好的文章,但几乎所有文章都使用某种 UI 技术,如 angular 或 thymleaf 来展示我发现难以掌握的概念。

我指的是下面的视频教程来学习弹簧安全性。

https://www.youtube.com/watch?v=payxWrmF_0k&list=PLqq-6Pq4lTTYTEooakHchTGglSvkZAjnE&index=6&t=0s

提前致谢!阿什帕拉布

标签: restspring-securitypostman-native-app

解决方案


  1. 通过邮递员发出GET请求http://localhost:8080/login,它会返回一个 html。从响应中提取_csrf令牌。它看起来像
   <input name="_csrf" type="hidden" 
          value="1c470a6c-dff3-43aa-9d08-d308545dc880" />
  1. 执行以下 POST 请求,将令牌、用户名和密码http://localhost:8080/login复制为表单参数_csrf

在此处输入图像描述

  1. 记下JESSIONID Cookie第二步的响应中的值。这就是authenticated session.

  2. 只要您将JESSIONID后续请求作为 cookie 发送,spring security 就会知道您是谁。Postman 会Cookie自动将其添加到后续请求中。

  3. 您可以手动将其添加为带有该 cookie 标头的标头,或更新邮递员设置以始终发送JESSIONIDcookie


推荐阅读