【Feign扩展】Feign支持BasicAuth验证

文章介绍了如何在微服务接口中增强安全性,特别是对重要接口使用BasicAuth鉴权。通过在FeignClient中添加自定义配置,创建BasicAuthRequestInterceptor,将账号密码配置在application.yaml中,并在请求头中添加Authorization。这样,每次请求都会自动附带鉴权信息。
摘要由CSDN通过智能技术生成

一、背景

一些比较重要的微服务,我们暴露的接口可能会希望安全性更高一些,此时,我们会给这些接口增加一些鉴权,如比较简单且方便的鉴权方式Basic Auth鉴权,此时,针对这些有Basic Auth鉴权的接口,我们该如何写Feign,其实是通过覆盖Feign的默认配置来支持鉴权。

二、 步骤

FeignClient的属性configuration增加自定义配置Configuration.class

@FeignClient(name = "mytest-server", configuration = Configuration.class)
public interface Client {
    //..
}

Configuration如下(特别注意,别加@Configuration注解,避免扫包扫到导致给全局的Feign都增加了BasicAuthRequestInterceptor拦截器):

/**
 * basic验证配置
 */
@EnableConfigurationProperties({Properties.class})
public class Configuration {
    @Autowired
    private Properties properties;
    public Configuration() {
    }
    @Bean
    public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
        return new BasicAuthRequestInterceptor(properties.getUsername(), properties.getPassword());
    }
}

其中Properties.java

/**
 * basic验证配置
 */
@ConfigurationProperties(prefix = "mytest")
@Data
public class Properties {
    private String username;
    private String password;
}

application.yaml增加basic auth账号密码配置如下:

mytest:
    username: test
    password: 123456

三、源码解析

核心就是请求头上添加Authorization=Basic xxx

public class BasicAuthRequestInterceptor implements RequestInterceptor {

  private final String headerValue;

  /**
   * Creates an interceptor that authenticates all requests with the specified username and password
   * encoded using ISO-8859-1.
   *
   * @param username the username to use for authentication
   * @param password the password to use for authentication
   */
  public BasicAuthRequestInterceptor(String username, String password) {
    this(username, password, ISO_8859_1);
  }

  /**
   * Creates an interceptor that authenticates all requests with the specified username and password
   * encoded using the specified charset.
   *
   * @param username the username to use for authentication
   * @param password the password to use for authentication
   * @param charset the charset to use when encoding the credentials
   */
  public BasicAuthRequestInterceptor(String username, String password, Charset charset) {
    checkNotNull(username, "username");
    checkNotNull(password, "password");
    this.headerValue = "Basic " + base64Encode((username + ":" + password).getBytes(charset));
  }

  /*
   * This uses a Sun internal method; if we ever encounter a case where this method is not
   * available, the appropriate response would be to pull the necessary portions of Guava's
   * BaseEncoding class into Util.
   */
  private static String base64Encode(byte[] bytes) {
    return Base64.encode(bytes);
  }

  @Override
  public void apply(RequestTemplate template) {
    template.header("Authorization", headerValue);
  }
}

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Feign是Netflix公司推出的一个轻量级的HTTP客户端,主要用于简化微服务之间的API调用。在使用Feign进行BASIC认证调用时,你可以按照以下步骤进行: 1. 添加依赖:在你的项目中添加Feign和相关的依赖,通常在Maven或Gradle的build.gradle文件中添加`feign`和`feign-basicauth`库。 ```xml <!-- Maven --> <dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-core</artifactId> <version>9.7.0</version> </dependency> <dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-basicauth</artifactId> <version>9.7.0</version> </dependency> // Gradle (Kotlin DSL) implementation("io.github.openfeign:feign-core:9.7.0") implementation("io.github.openfeign:feign-basicauth:9.7.0") ``` 2. 创建Feign接口:定义一个Feign接口,并用`@FeignClient`注解指定目标服务的URL。同时,使用`@RequestLine`注解定义API调用的HTTP方法和路径,用`@Headers`注解添加BASIC认证的Authorization头。 ```java import feign.RequestLine; import feign.Headers; @FeignClient(name = "your-service", url = "https://your-service.example.com") public interface BasicAuthClient { @RequestLine("GET /api/resource") @Headers("Authorization: Basic {username}:{password}") String getResource(String username, String password); } ``` 3. 配置基本认证:在Feign客户端启动类(通常是`Application`或`Main`)中,通过`Feign.Builder`实例化FeignClient时提供用户名和密码。 ```java import feign.Feign; @SpringBootApplication public class App { public static void main(String[] args) { try { // 假设username和password已经获取到 String username = "your-username"; String password = "your-password"; // 使用用户名和密码创建Basic Auth实例 BasicAuthClient client = Feign.builder() .credentials(username, password) .target(BasicAuthClient.class, "https://your-service.example.com"); // 调用Feign接口 String resource = client.getResource(username, password); System.out.println(resource); } catch (Exception e) { e.printStackTrace(); } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值