java - 从 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
因此,我们可以简单地通过请求转发它。
解决方案
您提供的代码片段适用于用例,即您的服务对用户进行身份验证。
但据我了解,您只想将凭据转发到另一个服务并让下游服务处理身份验证。
因此,凭证与“授权”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)中获取的。
了解更多信息:
推荐阅读
- lazarus - Free Pascal / Lazarus:为什么在我的示例中没有调用“FormCloseQuery”事件?
- opendaylight - 如何在 Opendaylight 中操作 YANG 生成的 REST API GET?
- c++ - 编译Qt项目,报错QQmlEngine: No such file or directory 编译终止
- twilio - Twilio - 如何在我的应用程序中获取请求检查员?
- javascript - Angular - Map/Catch 返回相同的值但收到错误
- javascript - setInterval 会阻止/干扰 node.js/express HTTP 服务器吗?
- python - 仅转置数据框中的几列和几行
- google-chrome-extension - 使用 Web 扩展清除 HTTP Basic Auth
- python - 通过在 pandas 中保留小时数进行分组
- c - 如果有两个空格,则将其计为 3 个单词