spring-cloud-example
微服务开发
git源码地址
1.微服务配置中心(config)和注册中心(eureka)
2.登录注册接口实例
3.token生成与校验
该服务将阐述Jwt生成token和校验的过程,重新编写登录注册等接口。
pom.xml添加所需的依赖包,如:mysql、jdbc、jpa等等
mysql
mysql-connector-java
org.springframework.boot
spring-boot-starter-jdbc
org.springframework.boot
spring-boot-starter-data-jpa
...
bootstrap.yml连接数据库,配置jpa等等
spring:
datasource:
url: jdbc:mysql://localhost:3306/autoTest?characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
...
创建所需的目录,目录结构如下:
代码编写
- Jwt的引入,生成token以及token的校验
public class JwtUtil {
// 过期时间为1小时
private static final long EXPIRE_TIME = 1*60*60*1000;
// token私钥
private static final String TOKEN_SECRET = "abc";
/**
* 生成签名,1小时后过期
* @param username
* @param id
* @return
*/
public static String sign(String username, Long id) {
// 过期时间
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
// 私钥及加密算法
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
// 设置头信息
HashMap header = new HashMap<>(2);
header.put("typ", "JWT");
header.put("alg", "HS256");
// 附带username和userId生成签名
return JWT.create().withHeader(header).withClaim("username", username)
.withClaim("userId", id).withExpiresAt(date).sign(algorithm);
}
/**
* token校验
*/
@SuppressWarnings("unused")
public static boolean verity(String token) {
try {
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT jwt = verifier.verify(token);
return true;
} catch (IllegalArgumentException e) {
// TODO: handle exception
return false;
} catch (JWTVerificationException e) {
// TODO: handle exception
return false;
}
}
}
- 对密码进行MD5加密
public class Util {
public static String stringMD5(String input) {
try {
// 拿到一个MD5转换器(如果想要SHA1参数换成”SHA1”)
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
// 输入的字符串转换成字节数组
byte[] inputByteArray = input.getBytes();
// inputByteArray是输入字符串转换得到的字节数组
messageDigest.update(inputByteArray);
// 转换并返回结果,也是字节数组,包含16个元素
byte[] resultByteArray = messageDigest.digest();
// 字符数组转换成字符串返回
return byreArrayToHex(resultByteArray);
} catch (NoSuchAlgorithmException e) {
// TODO: handle exception
return null;
}
}
public static String byreArrayToHex(byte[] byteArray) {
// 首先初始化一个字符数组,用来存放每个16进制字符
char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F' };
// new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方))
char[] resultCharArray = new char[byteArray.length * 2];
// 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去
int index = 0;
for (byte b : byteArray) {
resultCharArray[index++] = hexDigits[b>>> 4 & 0xf];
resultCharArray[index++] = hexDigits[b & 0xf];
}
// 字符数组组合成字符串返回
return new String(resultCharArray);
}
}
- Entity实体,定义表结构
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "user")
public class User {
/** id */
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/** 昵称 */
@Column(nullable = false)
private String username;
/** 手机 */
@Column(nullable = false)
private String mobile;
/** 密码 */
@Column(nullable = false)
private String password;
/** 创建时间 */
@JsonFormat(pattern="yyyy-MM-dd hh:mm:ss")
// @Column(nullable = false)
private Date created;
}
...
- Repository
@Repository
public interface UserRepository extends JpaRepository {
List getByUsername(String username);
}
- AjaxResult,用于定义接口的response
public class AjaxResult extends HashMap {
private static final long serialVersionUID = 1L;
public static final String CODE_TAG = "code";
public static final String MSG_TAG = "msg";
public static final String DATA_TAG = "data";
// 状态类型
public enum Type {
SUCCESS(0), // 成功
FAIL(1), // 失败
WARN(301), // 警告
ERROR(500); // 错误
private final int value;
Type(int value) {
this.value = value;
}
public int value() {
return this.value;
}
}
...
}
- Service,编写接口的service层。
@Service
public class UserService {
@Autowired
UserRepository userRepository;
/**
* 用户登录
* @param username
* @return
*/
public User checkUser(String username) {
List list = userRepository.getByUsername(username);
if (list != null && list.size() > 0) {
return list.get(0);
}
return null;
}
/**
* 用户注册
* @param user
* @return
*/
public User insert(User user) {
String username = user.getUsername();
Long time = System.currentTimeMillis();
user.setCreated(new Date(time));
String password = Util.stringMD5(user.getPassword()); // 对注册密码进行MD5加密
user.setPassword(password);
userRepository.save(user);
return this.geUser(username);
}
}
- Controller,对接口进行暴露及token的使用
@RestController
public class UserController {
@Autowired
UserService userService;
@PostMapping("/login")
@ResponseBody
public AjaxResult login(@RequestBody Map map) {
String username = map.get("username");
String password = map.get("password");
User user = userService.checkUser(username);
if (user != null) {
String pwd = Util.stringMD5(password);
String upwd = user.getPassword();
if (upwd.equals(pwd)) {
// 返回token
String token = JwtUtil.sign(username, user.getId()); // 对登录名和用户ID进行token生成
if (token != null) {
return AjaxResult.success("成功", token);
}
} else {
return AjaxResult.fail("密码不正确");
}
}
return AjaxResult.fail("用户不存在");
}
// 用户注册
@PostMapping("/register")
@ResponseBody
public AjaxResult register(@RequestBody User map) {
String username = map.getUsername();
String password = map.getPassword();
if (username != null && password != null) {
User user = userService.checkUser(username);
if (user == null) {
User u = userService.insert(map);
return AjaxResult.success("注册成功", u);
} else {
return AjaxResult.fail("用户名已存在");
}
} else {
return AjaxResult.fail("注册失败:用户名和密码不能为空");
}
}
...
}
以上是相关的逻辑代码示例,下面进行接口测试