授权微服务--前半部分:
1. Jwt与RSA加密
经分析,微服务间登录访问应实现无状态登录,我们采用Jwt与RSA进行非对称加密。地址:Jwt与RSA非对称
2. 授权中心
2.1 搭建项目
授权中心的主要职责:
- 用户鉴权:
- 接收用户的登录请求,通过用户中心的接口进行校验,通过后生成JWT
- 使用私钥生成JWT并返回
- 服务鉴权:微服务间的调用不经过Zuul,会有风险,需要鉴权中心进行认证
- 原理与用户鉴权类似,但逻辑稍微复杂一些(此处我们不做实现)
因为生成jwt,解析jwt这样的行为以后在其它微服务中也会用到,因此我们会抽取成工具。我们把鉴权中心进行聚合,一个工具module:ly-auth-common,一个提供服务的module: ly-auth-service。
2.1.1 引入依赖
2.1.1.1 父工程ly-auth
<?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</artifactId>
<groupId>com.leyou.parent</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.leyou.service</groupId>
<artifactId>ly-auth</artifactId>
<packaging>pom</packaging>
<modules>
<module>ly-auth-common</module>
<module>ly-auth-service</module>
</modules>
</project>
2.1.1.2 ly-auth-common
<?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>ly-auth</artifactId>
<groupId>com.leyou.service</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.leyou.service</groupId>
<artifactId>ly-auth-common</artifactId>
<dependencies>
<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.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
2.1.1.3 ly-auth-service
<?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>ly-auth</artifactId>
<groupId>com.leyou.service</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.leyou.service</groupId>
<artifactId>ly-auth-service</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.leyou.service</groupId>
<artifactId>ly-auth-common</artifactId>
<version>${leyou.latest.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.leyou.common</groupId>
<artifactId>ly-common</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.leyou.service</groupId>
<artifactId>ly-user-interface</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
2.1.2 配置
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 # 每隔5秒发送一次心跳
#lease-expiration-duration-in-seconds: 10 # 10秒不发送就过期
prefer-ip-address: true
ip-address: 127.0.0.1
#instance-id: ${spring.application.name}:${server.port}
ly:
jwt:
secret: ly@Login(Auth}*^31)&yun6%f3q2 # 登录校验的密钥
pubKeyPath: E:/course/JavaProject/javacode/idea/rsa/rsa.pub # 公钥地址
priKeyPath: E:/course/JavaProject/javacode/idea/rsa/rsa.pri # 私钥地址
expire: 30 # 过期时间,单位分钟
cookieName: LY_TOKEN
2.1.3 启动类
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class LyAuthApplication {
public static void main(String[] args) {
SpringApplication.run(LyAuthApplication.class, args);
}
}
2.1.4 添加网关路由
2.2 编写JWT工具
我们在ly-auth-coomon中编写一些通用的工具类:
2.2.1 RSA工具类
public class RsaUtils {
/**
* 从文件中读取公钥
*
* @param filename 公钥保存路径,相对于classpath
* @return 公钥对象
* @throws Exception
*/
public static PublicKey getPublicKey(String filename) throws Exception {
byte[] bytes = readFile(filename);
return getPublicKey(bytes);
}
/**
* 从文件中读取密钥
*
* @param filename 私钥保存路径,相对于classpath
* @return 私钥对象
* @throws Exception
*/
public static PrivateKey getPrivateKey(String filename) throws Exception {
byte[] bytes = readFile(filename);
return getPrivateKey(bytes);
}
/**
* 获取公钥
*
* @param bytes 公钥的字节形式
* @return
* @throws Exception
*/
public static PublicKey getPublicKey(byte[] bytes) throws Exception {
X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePublic(spec);
}
/**
* 获取密钥
*
* @param bytes 私钥的字节形式
* @return
* @throws Exception
*/
public static PrivateKey getPrivateKey(byte[] bytes) throws Exception {
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePrivate(spec);
}
/**
* 根据密文,生存rsa公钥和私钥,并写入指定文件
*
* @param publicKeyFilename 公钥文件路径
* @param privateKeyFilename 私钥文件路径
* @param secret 生成密钥的密文
* @throws IOException
* @throws NoSuchAlgorithmException
*/
public static void generateKey(String publicKeyFilename, String privateKeyFilename, String secret) throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom secureRandom = new SecureRandom(secret.getBytes());
keyPairGenerator.initialize(1024, secureRandom);
KeyPair keyPair = keyPairGenerator.genKeyPair();
// 获取公钥并写出
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
writeFile(publicKeyFilename, publicKeyBytes);
// 获取私钥并写出
byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
writeFile(privateKeyFilename, privateKeyBytes);
}
private static byte[] readFile(String fileName) throws Exception {
return Files.readAllBytes(new File(fileName).toPath());
}
private static void writeFile(String destPath, byte[] bytes) throws IOException {
File dest = new File(destPath);
if (!dest.exists()) {
dest.createNewFile();
}
Files.write(dest.toPath(), bytes);
}
}
2.2.2 常量类
其中定义了jwt中的payload的常用key
public abstract class JwtConstans {
public static final String JWT_KEY_ID = "id";
public static final String JWT_KEY_USER_NAME = "username";
}
2.2.3 对象工具类:
从jwt解析得到的数据是Object类型,转换为具体类型可能出现空指针,这个工具类进行了一些转换:
public class ObjectUtils {
public static String toString(Object obj) {
if (obj == null) {
return null;
}
return obj.toString();
}
public static Long toLong(Object obj) {
if (obj == null) {
return 0L;
}
if (obj instanceof Double || obj instanceof Float) {
return Long.valueOf(StringUtils.substringBefore(obj.toString(), "."));
}
if (obj instanceof Number) {
return Long.valueOf(obj.toString());
}
if (obj instanceof String) {
return Long.valueOf(obj.toString());
} else {
return 0L;
}
}
public static Integer toInt(Object obj) {
return toLong(obj).intValue();
}
}
2.2.4 载荷:UserInfo
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserInfo {
private Long id;
private String username;
}
2.2.5 JWT工具类
我们需要先在ly-auth-common中引入JWT依赖:
<dependencies>
<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>
</dependencies>
代码:
public class JwtUtils {
/**
* 私钥加密token
*
* @param userInfo 载荷中的数据
* @param privateKey 私钥
* @param expireMinutes 过期时间,单位秒
* @return
* @throws Exception
*/
public static String generateToken(UserInfo userInfo, PrivateKey privateKey, int expireMinutes) throws Exception {
return Jwts.builder()
.claim(JwtConstans.JWT_KEY_ID, userInfo.getId())
.claim(JwtConstans.JWT_KEY_USER_NAME, userInfo.getUsername())
.setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate())
.signWith(SignatureAlgorithm.RS256, privateKey)
.compact();
}
/**
* 私钥加密token
*
* @param userInfo 载荷中的数据
* @param privateKey 私钥字节数组
* @param expireMinutes 过期时间,单位秒
* @return
* @throws Exception
*/
public static String generateToken(UserInfo userInfo, byte[] privateKey, int expireMinutes) throws Exception {
return Jwts.builder()
.claim(JwtConstans.JWT_KEY_ID, userInfo.getId())
.claim(JwtConstans.JWT_KEY_USER_NAME, userInfo.getUsername())
.setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate())
.signWith(SignatureAlgorithm.RS256, RsaUtils.getPrivateKey(privateKey))
.compact();
}
/**
* 公钥解析token
*
* @param token 用户请求中的token
* @param publicKey 公钥
* @return
* @throws Exception
*/
private static Jws<Claims> parserToken(String token, PublicKey publicKey) {
return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
}
/**
* 公钥解析token
*
* @param token 用户请求中的token
* @param publicKey 公钥字节数组
* @return
* @throws Exception
*/
private static Jws<Claims> parserToken(String token, byte[] publicKey) throws Exception {
return Jwts.parser().setSigningKey(RsaUtils.getPublicKey(publicKey))
.parseClaimsJws(token);
}
/**
* 获取token中的用户信息
*
* @param token 用户请求中的令牌
* @param publicKey 公钥
* @return 用户信息
* @throws Exception
*/
public static UserInfo getInfoFromToken(String token, PublicKey publicKey) throws Exception {
Jws<Claims> claimsJws = parserToken(token, publicKey);
Claims body = claimsJws.getBody();
return new UserInfo(
ObjectUtils.toLong(body.get(JwtConstans.JWT_KEY_ID)),
ObjectUtils.toString(body.get(JwtConstans.JWT_KEY_USER_NAME))
);
}
/**
* 获取token中的用户信息
*
* @param token 用户请求中的令牌
* @param publicKey 公钥
* @return 用户信息
* @throws Exception
*/
public static UserInfo getInfoFromToken(String token, byte[] publicKey) throws Exception {
Jws<Claims> claimsJws = parserToken(token, publicKey);
Claims body = claimsJws.getBody();
return new UserInfo(
ObjectUtils.toLong(body.get(JwtConstans.JWT_KEY_ID)),
ObjectUtils.toString(body.get(JwtConstans.JWT_KEY_USER_NAME))
);
}
}
2.2.6 测试
我们在ly-auth-common中编写测试类:
public class JwtTest {
private static final String pubKeyPath = "D:\\heima\\rsa\\rsa.pub";
private static final String priKeyPath = "D:\\heima\\rsa\\rsa.pri";
private PublicKey publicKey;
private PrivateKey privateKey;
@Test
public void testRsa() throws Exception {
RsaUtils.generateKey(pubKeyPath, priKeyPath, "234");
}
//@Before
public void testGetRsa() throws Exception {
this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
}
@Test
public void testGenerateToken() throws Exception {
// 生成token
String token = JwtUtils.generateToken(new UserInfo(20L, "jack"), privateKey, 5);
System.out.println("token = " + token);
}
@Test
public void testParseToken() throws Exception {
String token = "eyJhbGciOiJSUzI1NiJ9.eyJpZCI6MjAsInVzZXJOYW1lIjoiamFjayIsImV4cCI6MTUyNzMzMDY5NX0.VpGNedy1z0aR262uAp2sM6xB4ljuxa4fzqyyBpZcGTBNLodIfuCNZkOjdlqf-km6TQPoz3epYf8cc_Rf9snsGdz4YPIwpm6X14JKU9jwL74q6zy61J8Nl9q7Zu3YnLibAvcnC_y9omiqKN8-iCi7-MvM-LwVS7y_Cx9eu0aaY8E";
// 解析token
UserInfo user = JwtUtils.getInfoFromToken(token, publicKey);
System.out.println("id: " + user.getId());
System.out.println("userName: " + user.getUsername());
}
}
2.2.6.1 测试生成公钥和私钥
我们运行这段代码:
运行之后,查看目标目录:
公钥和私钥已经生成了!
2.2.6.2 测试生成token
2.2.6.3 测试解析token
正常情况:
任意改动token,发现报错了:
2.3 编写登录授权接口
接下来,我们需要在ly-auth-servcice编写一个接口,对外提供登录授权服务。基本流程如下:
- 客户端携带用户名和密码请求登录
- 授权中心调用客户中心接口,根据用户名和密码查询用户信息
- 如果用户名密码正确,能获取用户,否则为空,则登录失败
- 如果校验成功,则生成JWT并返回
2.3.1 生成公钥和私钥
我们需要在授权中心生成真正的公钥和私钥。我们必须有一个生成公钥和私钥的secret,这个可以配置到application.yml中:
ly:
jwt:
secret: ly@Login(Auth}*^31)&yun6%f3q2 # 登录校验的密钥
pubKeyPath: E:/course/JavaProject/javacode/idea/rsa/rsa.pub # 公钥地址
priKeyPath: E:/course/JavaProject/javacode/idea/rsa/rsa.pri # 私钥地址
expire: 30 # 过期时间,单位分钟
cookieName: LY_TOKEN
然后编写属性类,加载这些数据:
package com.leyou.auth.config;
import com.leyou.auth.utils.RsaUtils;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;
@Data
@ConfigurationProperties(prefix = "ly.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);
// 对象一旦实例化后,就应该读取公钥和私钥
@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();
}
}
}
2.3.2 web
编写授权接口,我们接收用户名和密码,校验成功后,写入cookie中。
- 请求方式:post
- 请求路径:/accredit
- 请求参数:username和password
- 返回结果:无
代码:
@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {
@Autowired
private AuthService authService;
@Autowired
private JwtProperties prop;
@Value("${ly.jwt.cookieName}")
private String cookieName;
// 登录
@PostMapping("login")
public ResponseEntity<Void> login(
@RequestParam("username") String username,
@RequestParam("password") String password,
HttpServletResponse response,
HttpServletRequest request){
// 登录功能的实现
String token = authService.login(username, password);
CookieUtils.newBuilder(response).httpOnly().request(request).build(cookieName, token);
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
}
注:无需给前端浏览器返回token,token只有后端才需要使用,并且将token保存到cookie中
-
将token写入cookie — 工厂模式
-
httpOnly():避免别的js代码来操作你的cookie,是一种安全措施
-
charset(): 不需要编码 因为token中没有中文
-
maxAge(): cookie的生命周期,默认是-1,代表一次会话,浏览器关闭cookie就失效
-
response: 将cookie写入 — response中有一个方法 addCookie()
-
request: cookie中有域的概念 domain,不允许跨域, 例如一个cookie只能在www.baidu.com生效,无法在别的域下生效,给cookie绑定一个域,防止别的网站访问你的cookie,也是一种安全措施
2.3.3 CookieUtils
要注意,这里我们使用了一个工具类:CookieUtils,我们把它添加到ly-common中,然后引入servlet相关依赖即可:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
</dependency>
/**
* Cookie 工具类
*/
@Slf4j
public final class CookieUtils {
/**
* 得到Cookie的值, 不编码
*
* @param request
* @param cookieName
* @return
*/
public static String getCookieValue(HttpServletRequest request, String cookieName) {
return getCookieValue(request, cookieName, null);
}
/**
* 得到Cookie的值,
*
* @param request
* @param cookieName
* @return
*/
public static String getCookieValue(HttpServletRequest request, String cookieName, String charset) {
Cookie[] cookieList = request.getCookies();
if (cookieList == null || cookieName == null) {
return null;
}
String retValue = null;
try {
for (int i = 0; i < cookieList.length; i++) {
if (cookieList[i].getName().equals(cookieName)) {
if (charset != null && charset.length() > 0) {
retValue = URLDecoder.decode(cookieList[i].getValue(), charset);
} else {
retValue = cookieList[i].getValue();
}
break;
}
}
} catch (UnsupportedEncodingException e) {
log.error("Cookie Decode Error.", e);
}
return retValue;
}
public static CookieBuilder newBuilder(HttpServletResponse response) {
return new CookieBuilder(response);
}
public static class CookieBuilder {
private HttpServletRequest request;
private HttpServletResponse response;
private Integer maxAge;
private String charset;
private boolean httpOnly = false;
public CookieBuilder(HttpServletResponse response) {
this.response = response;
}
//防跨域访问
public CookieBuilder request(HttpServletRequest request) {
this.request = request;
return this;
}
//最大生命周期
public CookieBuilder maxAge(int maxAge) {
this.maxAge = maxAge;
return this;
}
//设置格式
public CookieBuilder charset(String charset) {
this.charset = charset;
return this;
}
//禁用JS访问
public CookieBuilder httpOnly() {
this.httpOnly = true;
return this;
}
//构建
public void build(String cookieName, String cookieValue) {
try {
if (StringUtils.isBlank(charset)) {
charset = "utf-8";
}
if (cookieValue == null) {
cookieValue = "";
} else if (StringUtils.isNotBlank(charset)) {
cookieValue = URLEncoder.encode(cookieValue, charset);
}
Cookie cookie = new Cookie(cookieName, cookieValue);
if (maxAge != null && maxAge > 0)
cookie.setMaxAge(maxAge);
if (null != request)// 设置域名的cookie
//todo
cookie.setDomain(getDomainName(request));
cookie.setPath("/");
cookie.setHttpOnly(httpOnly);
response.addCookie(cookie);
} catch (Exception e) {
log.error("Cookie Encode Error.", e);
}
}
/**
* 得到cookie的域名
*/
private String getDomainName(HttpServletRequest request) {
String domainName = null;
String serverName = request.getRequestURL().toString();
if (serverName == null || serverName.equals("")) {
domainName = "";
} else {
serverName = serverName.toLowerCase();
serverName = serverName.substring(7);
final int end = serverName.indexOf("/");
serverName = serverName.substring(0, end);
final String[] domains = serverName.split("\\.");
int len = domains.length;
if (len > 3) {
// www.xxx.com.cn
domainName = domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
} else if (len <= 3 && len > 1) {
// xxx.com or xxx.cn
domainName = domains[len - 2] + "." + domains[len - 1];
} else {
domainName = serverName;
}
}
if (domainName != null && domainName.indexOf(":") > 0) {
String[] ary = domainName.split("\\:");
domainName = ary[0];
}
return domainName;
}
}
}
2.3.4 UserClient
接下来我们肯定要对用户密码进行校验,所以我们需要通过FeignClient去访问 user-service微服务:
在ly-user-interface中编写接口 UserAPI:
编写FeignClient:
@FeignClient(value = "user-service")
public interface UserClient extends UserApi {
}
2.3.5 service
@Slf4j
@Service
@EnableConfigurationProperties(JwtProperties.class)
public class AuthService {
@Autowired
private UserClient userClient;
@Autowired
private JwtProperties prop;
// 登录
public String login(String username, String password) {
try {
// 校验用户名和密码
User user = userClient.queryUsernameAndPassword(username, password);
if (user == null) {
throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
}
// 生成token
String token = JwtUtils.generateToken(new UserInfo(user.getId(),username),prop.getPrivateKey(),prop.getExpire());
return token;
}catch (Exception e){
log.error("[授权中心] 用户名或者密码有误,用户名称:{}", username, e);
throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
}
}
}
2.3.6 测试
在页面上刷新,显示204登录成功
接下来我们查看首页cookie,却没有写入。
注:由于原因分析较复杂,且后续还有登录判断操作,因此分成两部分写。地址: 授权微服务–后半部分