技术栈:SpringBoot + Mybatis + SpringSecurity
程序地址:https://github.com/yaokuku123/spring-security
功能:实现分布式应用的单点登录。
一 分布式单点登录的架构
1.1 架构图
- 用户认证:这一环节主要是用户向认证服务器发起认证请求,认证服务器给用户返回一个成功的令牌token, 主要在认证服务器中完成,即图中的A系统,注意A系统只能有一个。
- 身份校验:这一环节是用户携带token去访问其他服务器时,在其他服务器中要对token的真伪进行检验,主 要在资源服务器中完成,即图中的B系统,这里B系统可以有很多个。
1.2 认证涉及的需要修改的过滤器方法
用户认证: 使用UsernamePasswordAuthenticationFilter过滤器中attemptAuthentication方法实现认证功能,该过滤 器父类中successfulAuthentication方法实现认证成功后的操作。
身份校验: 使用BasicAuthenticationFilter过滤器中doFilterInternal方法验证是否登录,以决定能否进入后续过滤器。
二 环境准备
2.1 构建基于角色的表格
/*
SQLyog Ultimate v12.08 (64 bit)
MySQL - 8.0.16 : Database - security_authority
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
/*Table structure for table `sys_permission` */
DROP TABLE IF EXISTS `sys_permission`;
CREATE TABLE `sys_permission` (
`ID` int(11) NOT NULL AUTO_INCREMENT COMMENT '编号',
`permission_NAME` varchar(30) DEFAULT NULL COMMENT '菜单名称',
`permission_url` varchar(100) DEFAULT NULL COMMENT '菜单地址',
`parent_id` int(11) NOT NULL DEFAULT '0' COMMENT '父菜单id',
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*Data for the table `sys_permission` */
/*Table structure for table `sys_role` */
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
`ID` int(11) NOT NULL AUTO_INCREMENT COMMENT '编号',
`ROLE_NAME` varchar(30) DEFAULT NULL COMMENT '角色名称',
`ROLE_DESC` varchar(60) DEFAULT NULL COMMENT '角色描述',
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
/*Data for the table `sys_role` */
/*Table structure for table `sys_role_permission` */
DROP TABLE IF EXISTS `sys_role_permission`;
CREATE TABLE `sys_role_permission` (
`RID` int(11) NOT NULL COMMENT '角色编号',
`PID` int(11) NOT NULL COMMENT '权限编号',
PRIMARY KEY (`RID`,`PID`),
KEY `FK_Reference_12` (`PID`),
CONSTRAINT `FK_Reference_11` FOREIGN KEY (`RID`) REFERENCES `sys_role` (`ID`),
CONSTRAINT `FK_Reference_12` FOREIGN KEY (`PID`) REFERENCES `sys_permission` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*Data for the table `sys_role_permission` */
/*Table structure for table `sys_user` */
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`password` varchar(120) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码',
`status` int(1) DEFAULT '1' COMMENT '1开启0关闭',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
/*Data for the table `sys_user` */
/*Table structure for table `sys_user_role` */
DROP TABLE IF EXISTS `sys_user_role`;
CREATE TABLE `sys_user_role` (
`UID` int(11) NOT NULL COMMENT '用户编号',
`RID` int(11) NOT NULL COMMENT '角色编号',
PRIMARY KEY (`UID`,`RID`),
KEY `FK_Reference_10` (`RID`),
CONSTRAINT `FK_Reference_10` FOREIGN KEY (`RID`) REFERENCES `sys_role` (`ID`),
CONSTRAINT `FK_Reference_9` FOREIGN KEY (`UID`) REFERENCES `sys_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*Data for the table `sys_user_role` */
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
2.2 在MySQL的表中添加几组数据用于测试
说明:
-
用户:xiaoming
密码:199748
拥有的角色:ROLE_USER,ROLE_PRODUCT
-
用户:xiaoma
密码:199748
拥有的角色:ROLE_USER,ROLE_ORDER
# sys_user表 password使用加密的方式存储 两者的密码明文为 199748
+----+----------+--------------------------------------------------------------+--------+
| id | username | password | status |
+----+----------+--------------------------------------------------------------+--------+
| 4 | xiaoming | $2a$10$9fSu8H/o/qKhRYm8N3IrGePdu5Kj3QNujaW5whHGyoi8ta0Bj4SSG | 1 |
| 5 | xiaoma | $2a$10$NJkRs/2AoD1iHlLNe4LwPu8M1ZvmVp4lsCD0QEqCoaRg1Jn2AG2hu | 1 |
+----+----------+--------------------------------------------------------------+--------+
# sys_role表
+----+--------------+--------------+
| ID | ROLE_NAME | ROLE_DESC |
+----+--------------+--------------+
| 6 | ROLE_USER | Basic Role |
| 7 | ROLE_PRODUCT | Product Role |
| 8 | ROLE_ORDER | Order Role |
| 9 | ROLE_ADMIN | Root |
+----+--------------+--------------+
# sys_user_role表
+-----+-----+
| UID | RID |
+-----+-----+
| 4 | 6 |
| 5 | 6 |
| 4 | 7 |
| 5 | 8 |
+-----+-----+
三 创建父工程
3.1 导入pom依赖(springboot)
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
四 创建通用模块
功能:json工具类,jwt工具类和rsa工具类。token的存储结构
4.1 导入pom依赖
<dependencies>
<!--jwt所需jar包-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.10.7</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.10.7</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.10.7</version>
<scope>runtime</scope>
</dependency>
<!--lombok插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--处理日期工具包-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<!--处理json工具包-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
<!--日志包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<!--测试包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
4.2 导入工具类
- 包结构
- Payload对象(为了方便后期获取token中的用户信息,将token中载荷部分单独封装成一个对象)
package com.yqj.domain;
import lombok.Data;
import java.util.Date;
/**
* 为了方便后期获取token中的用户信息,将token中载荷部分单独封装成一个对象
*/
@Data
public class Payload<T> {
private String id;
private T userInfo;
private Date expiration;
}
- json工具类
package com.yqj.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class JsonUtils {
public static final ObjectMapper mapper = new ObjectMapper();
private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);
public static String toString(Object obj) {
if (obj == null) {
return null;
}
if (obj.getClass() == String.class) {
return (String) obj;
}
try {
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
logger.error("json序列化出错:" + obj, e);
return null;
}
}
public static <T> T toBean(String json, Class<T> tClass) {
try {
return mapper.readValue(json, tClass);
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
public static <E> List<E> toList(String json, Class<E> eClass) {
try {
return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, eClass));
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
public static <K, V> Map<K, V> toMap(String json, Class<K> kClass, Class<V> vClass) {
try {
return mapper.readValue(json, mapper.getTypeFactory().constructMapType(Map.class, kClass, vClass));
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
public static <T> T nativeRead(String json, TypeReference<T> type) {
try {
return mapper.readValue(json, type);
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
}
- Jwt工具类(生成token以及校验token相关方法)
package com.yqj.utils;
import com.yqj.domain.Payload;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;
import java.util.UUID;
/**
* 生成token以及校验token相关方法
*/
public class JwtUtils {
private static final String JWT_PAYLOAD_USER_KEY = "user";
/**
* 私钥加密token
*
* @param userInfo 载荷中的数据
* @param privateKey 私钥
* @param expire 过期时间,单位分钟
* @return JWT
*/
public static String generateTokenExpireInMinutes(Object userInfo, PrivateKey privateKey, int expire) {
return Jwts.builder()
.claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(userInfo))
.setId(createJTI())
.setExpiration(DateTime.now().plusMinutes(expire).toDate())
.signWith(privateKey, SignatureAlgorithm.RS256)
.compact();
}
/**
* 私钥加密token
*
* @param userInfo 载荷中的数据
* @param privateKey 私钥
* @param expire 过期时间,单位秒
* @return JWT
*/
public static String generateTokenExpireInSeconds(Object userInfo, PrivateKey privateKey, int expire) {
return Jwts.builder()
.claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(userInfo))
.setId(createJTI())
.setExpiration(DateTime.now().plusSeconds(expire).toDate())
.signWith(privateKey, SignatureAlgorithm.RS256)
.compact();
}
/**
* 公钥解析token
*
* @param token 用户请求中的token
* @param publicKey 公钥
* @return Jws<Claims>
*/
private static Jws<Claims> parserToken(String token, PublicKey publicKey) {
return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
}
private static String createJTI() {
return new String(Base64.getEncoder().encode(UUID.randomUUID().toString().getBytes()));
}
/**
* 获取token中的用户信息
*
* @param token 用户请求中的令牌
* @param publicKey 公钥
* @return 用户信息
*/
public static <T> Payload<T> getInfoFromToken(String token, PublicKey publicKey, Class<T> userType) {
Jws<Claims> claimsJws = parserToken(token, publicKey);
Claims body = claimsJws.getBody();
Payload<T> claims = new Payload<>();
claims.setId(body.getId());
claims.setUserInfo(JsonUtils.toBean(body.get(JWT_PAYLOAD_USER_KEY).toString(), userType));
claims.setExpiration(body.getExpiration());
return claims;
}
/**
* 获取token中的载荷信息
*
* @param token 用户请求中的令牌
* @param publicKey 公钥
* @return 用户信息
*/
public static <T> Payload<T> getInfoFromToken(String token, PublicKey publicKey) {
Jws<Claims> claimsJws = parserToken(token, publicKey);
Claims body = claimsJws.getBody();
Payload<T> claims = new Payload<>();
claims.setId(body.getId());
claims.setExpiration(body.getExpiration());
return claims;
}
}
- rsa工具类
package com.yqj.utils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class RsaUtils {
private static final int DEFAULT_KEY_SIZE = 2048;
/**
* 从文件中读取公钥
*
* @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
*/
private static PublicKey getPublicKey(byte[] bytes) throws Exception {
bytes = Base64.getDecoder().decode(bytes);
X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePublic(spec);
}
/**
* 获取密钥
*
* @param bytes 私钥的字节形式
* @return
* @throws Exception
*/
private static PrivateKey getPrivateKey(byte[] bytes) throws NoSuchAlgorithmException, InvalidKeySpecException {
bytes = Base64.getDecoder().decode(bytes);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePrivate(spec);
}
/**
* 根据密文,生存rsa公钥和私钥,并写入指定文件
*
* @param publicKeyFilename 公钥文件路径
* @param privateKeyFilename 私钥文件路径
* @param secret 生成密钥的密文
*/
public static void generateKey(String publicKeyFilename, String privateKeyFilename, String secret, int keySize) throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom secureRandom = new SecureRandom(secret.getBytes());
keyPairGenerator.initialize(Math.max(keySize, DEFAULT_KEY_SIZE), secureRandom);
KeyPair keyPair = keyPairGenerator.genKeyPair();
// 获取公钥并写出
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
publicKeyBytes = Base64.getEncoder().encode(publicKeyBytes);
writeFile(publicKeyFilename, publicKeyBytes);
// 获取私钥并写出
byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
privateKeyBytes = Base64.getEncoder().encode(privateKeyBytes);
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);
}
}
4.3 编写测试类生成rsa的公私钥
作用:用于后续token的生成和解析(执行后,在对应目录下生成公私钥文件
package com.yqj;
import com.yqj.utils.RsaUtils;
import org.junit.jupiter.api.Test;
import java.security.PrivateKey;
import java.security.PublicKey;
/**
* Copyright(C),2019-2021,XXX公司
* FileName: RsaUtilsTest
* Author: yaoqijun
* Date: 2021/2/25 9:34
* 测试:使用RSA工具生成公私钥
*/
public class RsaUtilsTest {
private String privateKeyPath = "D:\\temp\\auth_key";
private String publicKeyPath = "D:\\temp\\auth_key.pub";
@Test
public void generateKey() throws Exception {
RsaUtils.generateKey(publicKeyPath,privateKeyPath,"yorick",2048);
}
@Test
public void getKey() throws Exception {
PublicKey publicKey = RsaUtils.getPublicKey(publicKeyPath);
PrivateKey privateKey = RsaUtils.getPrivateKey(privateKeyPath);
System.out.println("publicKey: "+publicKey.toString());
System.out.println("privateKey: "+privateKey.toString());
}
}
五 认证服务模块
5.1 导入pom依赖
<dependencies>
<dependency>
<groupId>com.yqj</groupId>
<artifactId>common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
</dependencies>
5.2 创建认证服务配置文件
server:
port: 9001
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql:///security_authority
username: root
password: 199748
mybatis:
type-aliases-package: com.yqj.domain
configuration:
map-underscore-to-camel-case: true
logging:
level:
com.yqj: debug
yqj:
key:
privateKeyPath: D:\\temp\\auth_key
publicKeyPath: D:\\temp\\auth_key.pub
5.3 公私钥配置类
package com.yqj.config;
import com.yqj.utils.RsaUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.security.PrivateKey;
import java.security.PublicKey;
/**
* Copyright(C),2019-2021,XXX公司
* FileName: RsaKeyProperties
* Author: yaoqijun
* Date: 2021/2/25 9:47
*/
@Data
@ConfigurationProperties("yqj.key")
public class RsaKeyProperties {
private String privateKeyPath;
private String publicKeyPath;
private PrivateKey privateKey;
private PublicKey publicKey;
@PostConstruct
public void loadKey() throws Exception {
privateKey = RsaUtils.getPrivateKey(privateKeyPath);
publicKey = RsaUtils.getPublicKey(publicKeyPath);
}
}
5.4 创建认证服务启动类
package com.yqj;
import com.yqj.config.RsaKeyProperties;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
/**
* Copyright(C),2019-2021,XXX公司
* FileName: AuthServerApplication
* Author: yaoqijun
* Date: 2021/2/25 9:50
*/
@SpringBootApplication
@MapperScan("com.yqj.mapper")
@EnableConfigurationProperties(RsaKeyProperties.class)
public class AuthServerApplication {
public static void main(String[] args) {
SpringApplication.run(AuthServerApplication.class,args);
}
}
5.5 编写数据库认证相关代码
- 认证对象类
- SysUser
package com.yqj.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.List;
/**
* Copyright(C),2019-2021,XXX公司
* FileName: SysUser
* Author: yaoqijun
* Date: 2021/2/24 10:14
*/
@Data
public class SysUser implements UserDetails {
private Integer id;
private String username;
private String password;
private List<SysRole> roles;
@JsonIgnore
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return roles;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@JsonIgnore
@Override
public boolean isAccountNonExpired() {
return true;
}
@JsonIgnore
@Override
public boolean isAccountNonLocked() {
return true;
}
@JsonIgnore
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@JsonIgnore
@Override
public boolean isEnabled() {
return true;
}
}
- SysRole
package com.yqj.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
/**
* Copyright(C),2019-2021,XXX公司
* FileName: SysRole
* Author: yaoqijun
* Date: 2021/2/24 10:15
*/
@Data
public class SysRole implements GrantedAuthority {
private Integer id;
private String roleName;
private String roleDesc;
@JsonIgnore
@Override
public String getAuthority() {
return roleName;
}
}
- 查询数据库信息的mapper类
- UserMapper
package com.yqj.mapper;
import com.yqj.domain.SysUser;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* Copyright(C),2019-2021,XXX公司
* FileName: UserMapper
* Author: yaoqijun
* Date: 2021/2/24 10:17
*/
public interface UserMapper {
@Select("select * from sys_user where username=#{username}")
@Results({
@Result(id = true, property = "id", column = "id"),
@Result(property = "roles", column = "id", javaType = List.class,
many = @Many(select = "com.yqj.mapper.RoleMapper.findByUid"))
})
public SysUser findByName(String username);
}
- RoleMapper
package com.yqj.mapper;
import com.yqj.domain.SysRole;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* Copyright(C),2019-2021,XXX公司
* FileName: RoleMapper
* Author: yaoqijun
* Date: 2021/2/24 10:18
*/
public interface RoleMapper {
@Select(" select r.id,r.role_name roleName,r.role_desc roleDesc " +
" from sys_role r,sys_user_role ur " +
" where r.id=ur.rid and ur.uid=#{uid} ")
public List<SysRole> findByUid(Integer uid);
}
- service服务
- Service接口
package com.yqj.service;
import org.springframework.security.core.userdetails.UserDetailsService;
/**
* Copyright(C),2019-2021,XXX公司
* FileName: UserService
* Author: yaoqijun
* Date: 2021/2/24 10:18
*/
public interface UserService extends UserDetailsService {
}
- Service的实现类
package com.yqj.service.impl;
import com.yqj.domain.SysUser;
import com.yqj.mapper.UserMapper;
import com.yqj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Copyright(C),2019-2021,XXX公司
* FileName: UserServiceImpl
* Author: yaoqijun
* Date: 2021/2/24 10:19
*/
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
SysUser user = userMapper.findByName(username);
return user;
}
}
5.6 编写认证过滤器
package com.yqj.filter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yqj.config.RsaKeyProperties;
import com.yqj.domain.SysRole;
import com.yqj.domain.SysUser;
import com.yqj.utils.JwtUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Copyright(C),2019-2021,XXX公司
* FileName: TokenLoginFilter
* Author: yaoqijun
* Date: 2021/2/25 9:55
*/
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {
private AuthenticationManager authenticationManager;
private RsaKeyProperties prop;
public TokenLoginFilter(AuthenticationManager authenticationManager, RsaKeyProperties prop) {
this.authenticationManager = authenticationManager;
this.prop = prop;
}
//接收并解析用户凭证,出現错误时,返回json数据前端
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
try {
//将json格式请求体转成JavaBean对象
SysUser user = new ObjectMapper().readValue(request.getInputStream(), SysUser.class);
return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
} catch (Exception e) {
try {
//如果认证失败,提供自定义json格式异常
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter out = response.getWriter();
Map<String,Object> map = new HashMap<>();
map.put("code",HttpServletResponse.SC_UNAUTHORIZED);
map.put("msg","账号或密码错误");
out.write(new ObjectMapper().writeValueAsString(map));
out.flush();
out.close();
} catch (Exception e1) {
throw new RuntimeException(e1);
}
throw new RuntimeException(e);
}
}
//用户登录成功后,生成token,并且返回json数据给前端
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
//得到当前认证的用户对象
SysUser user = new SysUser();
user.setUsername(authResult.getName());
user.setRoles((List<SysRole>) authResult.getAuthorities());
//json web token构建
String token = JwtUtils.generateTokenExpireInMinutes(user, prop.getPrivateKey(), 24 * 60);
//返回token
response.addHeader("Authorization","Bearer "+token);
//登录成功后,返回json格式进行提示
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
Map<String,Object> map = new HashMap<>();
map.put("code",HttpServletResponse.SC_OK);
map.put("msg","登录成功");
out.write(new ObjectMapper().writeValueAsString(map));
out.flush();
out.close();
}
}
5.7 编写检验token过滤器
package com.yqj.filter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yqj.config.RsaKeyProperties;
import com.yqj.domain.Payload;
import com.yqj.domain.SysUser;
import com.yqj.utils.JwtUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
/**
* Copyright(C),2019-2021,XXX公司
* FileName: TokenVerifyFilter
* Author: yaoqijun
* Date: 2021/2/25 10:15
*/
public class TokenVerifyFilter extends BasicAuthenticationFilter {
private RsaKeyProperties prop;
public TokenVerifyFilter(AuthenticationManager authenticationManager, RsaKeyProperties prop) {
super(authenticationManager);
this.prop = prop;
}
//过滤请求
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
//请求体的头中是否包含Authorization
String header = request.getHeader("Authorization");
//Authorization中是否包含Bearer,不包含直接返回
if (header == null || !header.startsWith("Bearer ")) {
chain.doFilter(request, response);
responseJson(response);
return;
}
//获取权限失败,会抛出异常
UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
////获取后,将Authentication写入SecurityContextHolder中供后序使用
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request, response);
} catch (Exception e) {
responseJson(response);
e.printStackTrace();
}
}
//未登录提示
private void responseJson(HttpServletResponse response) {
try {
//未登录提示
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
PrintWriter out = response.getWriter();
Map<String, Object> map = new HashMap<>();
map.put("code", HttpServletResponse.SC_FORBIDDEN);
map.put("message", "请登录!");
out.write(new ObjectMapper().writeValueAsString(map));
out.flush();
out.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
//获取token,并得到用户信息
private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
String token = request.getHeader("Authorization");
if (token != null) {
//通过token解析出载荷信息
Payload<SysUser> payload = JwtUtils.getInfoFromToken(token.replace("Bearer ", ""), prop.getPublicKey(), SysUser.class);
SysUser user = payload.getUserInfo();
//不为null,返回
if (user != null) {
return new UsernamePasswordAuthenticationToken(user, null, user.getRoles());
}
return null;
}
return null;
}
}
5.8 编写SpringSecurity配置类
package com.yqj.config;
import com.yqj.filter.TokenLoginFilter;
import com.yqj.filter.TokenVerifyFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* Copyright(C),2019-2021,XXX公司
* FileName: WebSecurityConfig
* Author: yaoqijun
* Date: 2021/2/25 10:33
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private RsaKeyProperties prop;
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
//关闭跨站请求防护
.cors()
.and()
.csrf().disable()
.authorizeRequests()
//允许不登陆就可以访问的方法,多个用逗号分隔
.antMatchers("/product").hasAnyRole("USER")
//其他的需要授权后访问
.anyRequest().authenticated()
.and()
//增加自定义认证过滤器
.addFilter(new TokenLoginFilter(authenticationManager(),prop))
//增加自定义验证认证过滤器
.addFilter(new TokenVerifyFilter(authenticationManager(),prop))
//前后端分离是无状态的,不用session了,直接禁用。
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
六 资源服务模块
6.1 配置pom依赖
<dependencies>
<dependency>
<groupId>com.yqj</groupId>
<artifactId>common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
</dependencies>
6.2 编写产品服务配置文件
server:
port: 9002
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql:///security_authority
username: root
password: 199748
mybatis:
type-aliases-package: com.yqj.domain
configuration:
map-underscore-to-camel-case: true
logging:
level:
com.yqj: debug
yqj:
key:
publicKeyPath: D:\\temp\\auth_key.pub
6.3 编写读取公钥的配置类
package com.yqj.config;
import com.yqj.utils.RsaUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import javax.annotation.PostConstruct;
import java.security.PublicKey;
/**
* Copyright(C),2019-2021,XXX公司
* FileName: RsaKeyProperties
* Author: yaoqijun
* Date: 2021/2/25 11:04
*/
@Data
@ConfigurationProperties("yqj.key")
public class RsaKeyProperties {
private String publicKeyPath;
private PublicKey publicKey;
@PostConstruct
public void loadKey() throws Exception {
publicKey = RsaUtils.getPublicKey(publicKeyPath);
}
}
6.4 编写启动类
package com.yqj;
import com.yqj.config.RsaKeyProperties;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
/**
* Copyright(C),2019-2021,XXX公司
* FileName: AuthProductApplication
* Author: yaoqijun
* Date: 2021/2/25 11:05
*/
@SpringBootApplication
@MapperScan("com.yqj.mapper")
@EnableConfigurationProperties(RsaKeyProperties.class)
public class AuthProductApplication {
public static void main(String[] args) {
SpringApplication.run(AuthProductApplication.class,args);
}
}
6.5 复制认证服务模块的用户对象,角色对象,和校验认证过滤器
6.6 SpringSecurity配置类
package com.yqj.config;
import com.yqj.filter.TokenVerifyFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
/**
* Copyright(C),2019-2021,XXX公司
* FileName: WebSecurityConfig
* Author: yaoqijun
* Date: 2021/2/25 11:07
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private RsaKeyProperties prop;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/product").hasAnyRole("USER")
.anyRequest().authenticated()
.and()
.addFilter(new TokenVerifyFilter(authenticationManager(),prop))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
6.7 编写产品处理器
package com.yqj.controller;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Copyright(C),2019-2021,XXX公司
* FileName: ProductController
* Author: yaoqijun
* Date: 2021/2/25 11:20
*/
@RestController
@RequestMapping("/product")
public class ProductController {
@Secured("ROLE_PRODUCT")
@GetMapping("/findAll")
public String findAll(){
return "9002 success findAll...";
}
}
七 测试
- 向认证服务器发起认证请求
- 得到认证成功的返回结果,并将token放入header中
- 申请访问资源服务中的方法,未携带token,拒绝访问
- 携带token再次申请资源服务的方法