此博客用于个人学习,来源于网上,对知识点进行一个整理。
1. 无状态登录原理:
1.1 什么是有状态?
有状态服务,即服务端需要记录每次会话的客户端信息,从而识别客户端身份,根据用户身份进行请求的处理,典型的设计如 tomcat 中的 session。
例如登录:用户登录后,我们把登录者的信息保存在服务端 session 中,并且给用户一个 cookie 值,记录对应的 session。然后下次请求,用户携带 cookie 值来,我们就能识别到对应 session,从而找到用户的信息。
缺点是什么?
- 服务端保存大量数据,增加服务端压力
- 服务端保存用户状态,无法进行水平扩展
- 客户端请求依赖服务端,多次请求必须访问同一台服务器
1.2 什么是无状态:
微服务集群中的每个服务,对外提供的都是Rest风格的接口。而 Rest 风格的一个最重要的规范就是:服务的无状态性,即:
- 服务端不保存任何客户端请求者信息
- 客户端的每次请求必须具备自描述信息,通过这些信息识别客户端身份
带来的好处是什么呢?
- 客户端请求不依赖服务端的信息,任何多次请求不需要必须访问到同一台服务
- 服务端的集群和状态对客户端透明
- 服务端可以任意的迁移和伸缩
- 减小服务端存储压力
1.3 如何实现无状态:
无状态登录的流程:
- 当客户端第一次请求服务时,服务端对用户进行信息认证(登录)
- 认证通过,将用户信息进行加密形成 token,返回给客户端,作为登录凭证
- 以后每次请求,客户端都携带认证的 token
- 服务的对 token 进行解密,判断是否有效
整个登录过程中,最关键的点是 token 的安全性。
token 是识别客户端身份的唯一标示,我们将采用 JWT + RSA 非对称加密。
1.4 JWT:
1)JWT,全称是 Json Web Token, 是 JSON 风格轻量级的授权和身份认证规范,可实现无状态、分布式的 Web 应用授权。
2)数据格式:
JWT包含三部分数据:
-
Header:头部,通常头部有两部分信息:(会对头部进行 base64 编码,得到第一部分数据)
- 声明类型,这里是 JWT
-
Payload:载荷,就是有效数据,一般包含下面信息:(这部分也会采用 base64 编码,得到第二部分数据)
- 用户身份信息(注意,这里因为采用 base64 编码,可解码,因此不要存放敏感信息)
- 注册声明:如 token 的签发时间,过期时间,签发人等
-
Signature:签名,是整个数据的认证信息。一般根据前两步的数据,再加上服务的的密钥(secret)(不要泄漏,最好周期性更换),通过加密算法生成。用于验证整个数据完整和可靠性
生成的数据格式:token ==个人证件 jwt =个人身份证
3)JWT 交互流程:
步骤:
- 1、用户登录
- 2、服务的认证,通过后根据 secret 生成 token
- 3、将生成的 token 返回给浏览器
- 4、用户每次请求携带 token
- 5、服务端利用公钥解读 jwt 签名,判断签名有效后,从 Payload 中获取用户信息
- 6、处理请求,返回响应结果
因为 JWT 签发的 token 中已经包含了用户的身份信息,并且每次请求都会携带,这样服务的就无需保存用户信息,甚至无需去数据库查询,完全符合了 Rest 的无状态规范。
4)非对称加密:
加密技术是对信息进行编码和解码的技术,编码是把原来可读信息(又称明文)译成代码形式(又称密文),其逆过程就是解码(解密),加密技术的要点是加密算法,加密算法可以分为三类:
- 对称加密,如 AES
- 基本原理:将明文分成N个组,然后使用密钥对各个组进行加密,形成各自的密文,最后把所有的分组密文进行合并,形成最终的密文。
- 优势:算法公开、计算量小、加密速度快、加密效率高
- 缺陷:双方都使用同样密钥,安全性得不到保证
- 非对称加密,如 RSA
- 基本原理:同时生成两把密钥:私钥和公钥,私钥隐秘保存,公钥可以下发给信任客户端
- 私钥加密,持有私钥或公钥才可以解密
- 公钥加密,持有私钥才可解密
- 优点:安全,难以破解
- 缺点:算法比较耗时
- 基本原理:同时生成两把密钥:私钥和公钥,私钥隐秘保存,公钥可以下发给信任客户端
- 不可逆加密,如 MD5,SHA
- 基本原理:加密过程中不需要使用密钥,输入明文后由系统直接经过加密算法处理成密文,这种加密后的数据是无法被解密的,无法根据密文推算出明文
1.5 结合 Zuul 的鉴权流程:
secret 是签名的关键,因此一定要保密,我们放到鉴权中心保存,其它任何服务中都不能获取 secret。
1)没有 RSA 加密时:
在微服务架构中,我们可以把服务的鉴权操作放到网关中,将未通过鉴权的请求直接拦截,如图:
- 用户请求登录
- Zuul 将请求转发到授权中心,请求授权
- 授权中心校验完成,颁发 JWT 凭证
- 客户端请求其它功能,携带 JWT
- Zuul 将 jwt 交给授权中心校验,通过后放行
- 用户请求到达微服务
- 微服务将 jwt 交给鉴权中心,鉴权同时解析用户信息
- 鉴权中心返回用户数据给微服务
- 微服务处理请求,返回响应
每次鉴权都需要访问鉴权中心,系统间的网络请求频率过高,效率略差,鉴权中心的压力较大。
2)结合 RSA 的鉴权:
- 我们首先利用 RSA 生成公钥和私钥。私钥保存在授权中心,公钥保存在 Zuul 和各个信任的微服务
- 用户请求登录
- 授权中心校验,通过后用私钥对 JWT 进行签名加密
- 返回 jwt 给用户
- 用户携带 JWT 访问
- Zuul 直接通过公钥解密 JWT,进行验证,验证通过则放行
- 请求到达微服务,微服务直接用公钥解析 JWT,获取用户信息,无需访问授权中心
2. 授权中心:
2.1 创建授权中心:
授权中心的主要职责:
- 用户鉴权:
- 接收用户的登录请求,通过用户中心的接口进行校验,通过后生成JWT
- 使用私钥生成 JWT 并返回
- 服务鉴权:微服务间的调用不经过 Zuul,会有风险,需要鉴权中心进行认证
- 原理与用户鉴权类似,但逻辑稍微复杂一些
因为生成 jwt,解析 jwt 这样的行为以后在其它微服务中也会用到,因此我们会抽取成工具。我们把鉴权中心进行聚合,一个工具 module,一个提供服务的 module。
1)创建 module,命名为 leyou-auth,采用 maven 的方式创建。
2)在 leyou-auth 的基础上,创建授权通用模块 module : leyou-auth-common。
pom.xml:
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>leyou-auth</artifactId>
<groupId>com.leyou.parent</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.leyou.auth</groupId>
<artifactId>leyou-auth-common</artifactId>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
3)在 leyou-auth 的基础上,创建授权通用模块 module : leyou-auth-service。
pom.xml:
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>leyou-auth</artifactId>
<groupId>com.leyou.parent</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.leyou.auth</groupId>
<artifactId>leyou-auth-service</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>com.leyou.auth</groupId>
<artifactId>leyou-auth-common</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.leyou.common</groupId>
<artifactId>leyou-common</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
引导类:
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class LeyouAuthApplication {
public static void main(String[] args) {
SpringApplication.run(LeyouAuthApplication.class, args);
}
}
application.yml
server:
port: 8087
spring:
application:
name: auth-service
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
registry-fetch-interval-seconds: 10
instance:
lease-renewal-interval-in-seconds: 5
lease-expiration-duration-in-seconds: 15
在 leyou-gateway 工程的 application.yml 中,修改路由:
zuul:
prefix: /api
routes:
item-service: /item/** #路由到商品的微服务
search-service: /search/** #路由到搜索微服务
user-service: /user/** #用户微服务
auth-service: /auth/** # 授权中心微服务
2.2 编写登录授权接口:
接下来,我们需要在 leyou-auth-servcice 编写一个接口,对外提供登录授权服务。基本流程如下:
- 客户端携带用户名和密码请求登录
- 授权中心调用用户中心接口,根据用户名和密码查询用户信息
- 如果用户名密码正确,能获取用户,否则为空,则登录失败
- 如果校验成功,则生成 JWT 并返回
1)生成公钥和私钥:
我们需要在授权中心生成真正的公钥和私钥。我们必须有一个生成公钥和私钥的 secret,这个可以配置到 application.yml 中:
leyou:
jwt:
secret: leyou@Login(Auth}*^31)&heiMa% # 登录校验的密钥
pubKeyPath: C:\\tmp\\rsa\\rsa.pub # 公钥地址
priKeyPath: C:\\tmp\\rsa\\rsa.pri # 私钥地址
expire: 30 # 过期时间,单位分钟
然后编写属性类,加载这些数据:
@ConfigurationProperties(prefix = "leyou.jwt")
public class JwtProperties {
private String secret; // 密钥
private String pubKeyPath;// 公钥
private String priKeyPath;// 私钥
private int expire;// token过期时间
private String cookieName;
private PublicKey publicKey; // 公钥
private PrivateKey privateKey; // 私钥
private static final Logger logger = LoggerFactory.getLogger(JwtProperties.class);
/**
* @PostContruct:在构造方法执行之后执行该方法
*/
@PostConstruct
public void init(){
try {
File pubKey = new File(pubKeyPath);
File priKey = new File(priKeyPath);
if (!pubKey.exists() || !priKey.exists()) {
// 生成公钥和私钥
RsaUtils.generateKey(pubKeyPath, priKeyPath, secret);
}
// 获取公钥和私钥
this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
} catch (Exception e) {
logger.error("初始化公钥和私钥失败!", e);
throw new RuntimeException();
}
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getPubKeyPath() {
return pubKeyPath;
}
public void setPubKeyPath(String pubKeyPath) {
this.pubKeyPath = pubKeyPath;
}
public String getPriKeyPath() {
return priKeyPath;
}
public void setPriKeyPath(String priKeyPath) {
this.priKeyPath = priKeyPath;
}
public int getExpire() {
return expire;
}
public void setExpire(int expire) {
this.expire = expire;
}
public String getCookieName() {
return cookieName;
}
public void setCookieName(String cookieName) {
this.cookieName = cookieName;
}
public PublicKey getPublicKey() {
return publicKey;
}
public void setPublicKey(PublicKey publicKey) {
this.publicKey = publicKey;
}
public PrivateKey getPrivateKey() {
return privateKey;
}
public void setPrivateKey(PrivateKey privateKey) {
this.privateKey = privateKey;
}
public static Logger getLogger() {
return logger;
}
}
2)Controller:
编写授权接口,我们接收用户名和密码,校验成功后,写入 cookie 中。
- 请求方式:post
- 请求路径:/accredit
- 请求参数:username 和 password
- 返回结果:无
@Controller
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {
@Autowired
private AuthService authService;
@Autowired
private JwtProperties jwtProperties;
/**
* 登录授权
* @param username
* @param password
* @param request
* @param response
* @return
*/
@PostMapping("accredit")
public ResponseEntity<Void> accredit(
@RequestParam("username")String username,
@RequestParam("password")String password,
HttpServletRequest request,
HttpServletResponse response
){
String token = this.authService.accredit(username,password);
if (StringUtils.isBlank(token)){
//未经许可,未经授权
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
CookieUtils.setCookie(request,response,this.jwtProperties.getCookieName(),token,this.jwtProperties.getExpire()*60);
return ResponseEntity.ok(null);
}
}
这里的 cookie 的 name 和生存时间,我们配置到属性文件:application.yml:
cookieName: LY_TOKEN
cookieMaxAge: 30
3)UserClient:
接下来我们肯定要对用户密码进行校验,所以我们需要通过 FeignClient 去访问 user-service 微服务:
在 leyou-auth 中引入 user-service-interface 依赖:
<dependency>
<groupId>com.leyou.user</groupId>
<artifactId>leyou-user-interface</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
参照 leyou-search 或者 leyou-goods-web,在 leyou-auth-service 中编写 FeignClient:
@FeignClient(value = "user-service")
public interface UserClient extends UserApi {
}
在 leyou-user-interface 工程中添加 api 接口:
public interface UserApi {
@GetMapping("query")
public User queryUser(@RequestParam("username")String username, @RequestParam("password")String password);
}
4)AuthService:
在 leyou-auth-service:
@Service
public class AuthService {
@Autowired
private UserClient userClient;
@Autowired
private JwtProperties jwtProperties;
public String accredit(String username, String password) {
//1.根据用户名和密码查询
User user = this.userClient.queryUser(username,password);
//2.判断user
if (user == null){
return null;
}
try {
//3.jwtUtils生成jwt类型的token
UserInfo userInfo = new UserInfo();
userInfo.setId(user.getId());
userInfo.setUsername(user.getUsername());
return JwtUtils.generateToken(userInfo,this.jwtProperties.getPrivateKey(),this.jwtProperties.getExpire());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}