跳到主要内容

【23】OAuth2FeignRequestInterceptor、BasicAuthRequestInterceptor拦截器解析

> 有道无术,术尚可求,有术无道,止于术。 > > 资料整理来自网络

文章目录

    • BasicAuthRequestInterceptor
    • Basic 认证
    • 使用案例
    • 源码
  • OAuth2FeignRequestInterceptor
    • 源码分析
    • 应用场景
    • 使用案例

BasicAuthRequestInterceptor

BasicAuthRequestInterceptor翻译过来就是 Basic 认证请求拦截器。

Basic 认证

Basic认证是一种较为简单的HTTP认证方式,客户端通过明文(Base64编码格式)传输用户名和密码到服务端进行认证,通常需要配合HTTPS来保证信息传输的安全。

比如Security 就支持这种方式,在发送认证请求时,按照以下格式:

// 请求头Authorization 添加Basic 认证信息
Authorization: Basic 用户名:密码Base64编码格式

使用案例

首先注入一个BasicAuthRequestInterceptor

    @Bean
BasicAuthRequestInterceptor basicAuthRequestInterceptor(){


return new BasicAuthRequestInterceptor("zhangsan","123456");
}

然后使用Feign调用远程服务,可以在日志中看到在消息头中添加了Basic认证信息:

 

源码

源码也很简单,就是将用户名密码,经过编码后放入到消息头中:

public class BasicAuthRequestInterceptor implements RequestInterceptor {


private final String headerValue;

public BasicAuthRequestInterceptor(String username, String password) {


this(username, password, Util.ISO_8859_1);
}

public BasicAuthRequestInterceptor(String username, String password, Charset charset) {


Util.checkNotNull(username, "username", new Object[0]);
Util.checkNotNull(password, "password", new Object[0]);
this.headerValue = "Basic " + base64Encode((username + ":" + password).getBytes(charset));
}

private static String base64Encode(byte[] bytes) {


return Base64.encode(bytes);
}

public void apply(RequestTemplate template) {


template.header("Authorization", new String[]{

this.headerValue});
}
}