创建jwt工具类
1.在子模块util中创建java文件
package com.mengxuegu.member.util;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component //生成组件,到时候引用
@ConfigurationProperties(prefix = "mengxuegu.jwt.config") //其他模块中进行配置
public class jwtUtil {
// 密钥
private String secretKey;
//单位秒,默认7天
private long expires = 60*60*24*7;
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public long getExpires() {
return expires;
}
public void setExpires(long expires) {
this.expires = expires;
}
/**
* 生成JWT
* @param id
*/
public String createJWT(String id, String subject, Boolean isLogin) {
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
JwtBuilder builder = Jwts.builder().setId(id)
.setSubject(subject)
.setIssuedAt(now)
.signWith(SignatureAlgorithm.HS256, secretKey)
.claim("isLogin", isLogin);
if (expires > 0) {
// expires乘以1000是毫秒转秒
builder.setExpiration(new Date(nowMillis + expires*1000));
}
return builder.compact();
}
/**
* 解析JWT
* @param jwtToken
*/
public Claims parseJWT(String jwtToken){
return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwtToken).getBody();
}
}
2.子模块api的配置文件中配置jwt的密钥和过期时间
mengxuegu:
jwt:
config:
secretKey: mengxuegu # jwt令牌密钥
expires: 604800 # 单位秒,7天
身份认证的实现逻辑
1.service
// 登录用户生成密钥
Result login(String username,String password);
2.serviceImpl
@Autowired
private jwtUtil jwtUtil;
@Override
public Result login(String username, String password) {
if(StringUtils.isBlank(username) || StringUtils.isBlank(password)){
return Result.error("用户名或密码错误");
}
/* 通过用户名查询该用户信息,
若信息不存在,返回错误;
若信息存在,查询密码是否正确;
密码正确,生成token;
密码不正确,返回错误;*/
Staff staff = getByUsername(username);
if(staff == null){
return Result.error("用户名或密码错误");
}
boolean b = new BCryptPasswordEncoder().matches(password, staff.getPassword());
if(!b){
return Result.error("用户名或密码错误");
}
// 登陆成功后,将生成的token返回给客户端用户
// 创建map键值对
String token = jwtUtil.createJWT(staff.getId()+"", staff.getName(), true);
Map<String,String> map=new HashMap<>();
map.put("token",token);
return Result.ok(map);
}
//通过用户名获取用户
public Staff getByUsername(String username){
QueryWrapper<Staff> query=new QueryWrapper<>();
query.eq("username",username);
return baseMapper.selectOne(query);
}
3.controller
/ 登录
@PostMapping("/login")
public Result login(@RequestBody Staff staff){
return staffService.login(staff.getUsername(),staff.getPassword());
}