首页 > 解决方案 > 从 Postman 请求 Spring Boot 中读取 Basic Authorization 的用户名和密码值

问题描述

我很新Spring-boot,我正在构建微服务,它将简单地将请求转发到其他系统进行处理(JSON 到 XML)。为此,连同请求,我需要设置用户名和密码,所以到目前为止,我在谷歌上只找到了下面的片段。

@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyBasicAuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
          .withUser("user1").password(passwordEncoder().encode("user1Pass"))
          .authorities("ROLE_USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
          .antMatchers("/securityNone").permitAll()
          .anyRequest().authenticated()
          .and()
          .httpBasic()
          .authenticationEntryPoint(authenticationEntryPoint);

        http.addFilterAfter(new CustomFilter(),
          BasicAuthenticationFilter.class);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

在这里,它是硬编码的,我们不需要这个,也不想维护database. 我正在尝试获取控制器中(基本授权)Auth选项卡的用户名和密码。Postman因此,我们可以简单地通过请求转发它。

标签: javaspringspring-bootspring-security

解决方案


您提供的代码片段适用于用例,即您的服务对用户进行身份验证。

但据我了解,您只想将凭据转发到另一个服务并让下游服务处理身份验证。

因此,凭证与“授权”HTTP 标头 [1] 一起发送。如果你想访问它们,你可以简单地从请求(HttpServletRequest.java [2,3])中获取它,如下所示:

public ResponseEntity<DemoClass> getDemo(HttpServletRequest request) {
    final String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
    // ...

您获得的值是 Base64[4] 编码的,因此您必须对其进行解码。

例如,用户名“username”和密码“password”的基本授权如下所示:

基本 dXNlcm5hbWU6cGFzc3dvcmQ=

首先,必须删除前缀“Basic”,然后您只有用户名和密码 Base64 编码。解码后是:

用户名密码

一种更简单的方法是从用户请求中获取 Authorization 标头并将其放入您的请求中。

例如,如下所示:

OkHttpClient client = new OkHttpClient().newBuilder()
  .build();

Request request = new Request.Builder()
  .url("http://localhost:8080/")
  .method("GET", null)
  .addHeader("Authorization", "Basic dXNlcm5hbWU6cGFzc3dvcmQ=") // Client credentials from the header
  .build();

注意:我只是从邮递员示例(Java - OkHttp)中获取的。

了解更多信息:

  1. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization
  2. https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html
  3. https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html#getHeader-java.lang.String-
  4. https://en.wikipedia.org/wiki/Base64

推荐阅读