简介
在开发和一些集成测试中,请求调用需要基于登录,在请求中需要携带登录后得到的token等信息,本篇文章对于这种场景进行了探索
背景信息说明
本地实验的有三个组成部分:
- 登录服务:提供用户登录等服务,调用登录接口后,得到后序的token信息
- 业务服务:业务的接口服务,访问接口都需要进行登录验证
- 测试服务:可以当成一个集成测试工程,首先访问登录服务进行登录,得到token信息,然后去访问业务服务
登录服务和业务服务,本篇中不进行说明,本篇中的登录服务和业务服务的登录认证是基于SaToken进行搭建的,可以参考博主之前的一篇文章:Sa-Token 单点登录 SSO模式二 URL重定向传播会话示例
闲话不多说,下面开始测试服务的代码说明
Maven配置信息
工程中使用spring基础和feign,是一个单独的工程,配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.self.growth</groupId>
<artifactId>integration-test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>integration-test</name>
<description>integration-test</description>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>3.1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
工程配置信息
我们需要进行一些配置,如下:
test:
# 登录服务的用户名和密码
login:
username: username
password: password
server:
# 业务服务的请求地址
record:
url: http://localhost:9050
# 登录服务的请求地址
auth:
url: http://localhost:9000
spring:
main:
allow-bean-definition-overriding: true
Feign客户端与拦截器配置
登录服务的客户端定义如下:
package com.self.growth.integration.test.feign;
import com.self.growth.integration.test.vo.ResResult;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(
value = "UserClient",
url = "${test.server.auth.url}"
)
public interface UserClient {
@RequestMapping(method = RequestMethod.GET, value = "/sso/doLogin")
ResponseEntity<ResResult<Void>> login(@RequestParam("name") String name, @RequestParam("pwd") String pwd);
}
上面定义了客户端的请求url&