第一:添加依赖
<dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.5.0</version> </dependency>
第二步:添加JWT实体类
import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.DecodedJWT; import java.util.Date; import java.util.HashMap; public class JwtUtil { /** * 过期时间为1天 */ private static final long EXPIRE_TIME = 24*60*60*1000; /** * Token私钥 */ private static final String TOKEN_SECRET = "onesmile123123123"; /** * 生成签名,15分钟后过期 * @param username * @param userId */ public static String sign(String username,String userId){ //过期时间 Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME); //私钥及加密算法 Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET); //设置头信息 HashMap<String,Object> header = new HashMap<>(2); header.put("typ","JWT"); header.put("alg","HS256"); //附带username和userId生成签名 return JWT.create().withHeader(header).withClaim("loginName",username) .withClaim("userId",userId).withExpiresAt(date).sign(algorithm); } 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 (Exception e){ e.printStackTrace(); return false; } } }
第三步:创建User实体类
import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "one_user") public class User { @Id @Column private Integer id; //用户id @Column private String user_code; //用户姓名 @Column private String user_pass; //用户密码 @Column private String s_id; //用户对应操作系统id public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUser_code() { return user_code; } public void setUser_code(String user_code) { this.user_code = user_code; } public String getUser_pass() { return user_pass; } public void setUser_pass(String user_pass) { this.user_pass = user_pass; } public String getS_id() { return s_id; } public void setS_id(String s_id) { this.s_id = s_id; } @Override public String toString() { return "User{" + "id=" + id + ", user_code='" + user_code + '\'' + ", user_pass='" + user_pass + '\'' + ", s_id='" + s_id + '\'' + '}'; } }
第四步:创建响应状态
import java.util.HashMap; public class AjaxResult extends HashMap<String,Object> { 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; } } /** * 状态类型 */ private Type type; /**状态码*/ private int code; /**返回内容*/ private String msg; /**数据对象*/ private Object data; /** * 初始化一个新创建的AjaxResult对象,使其表示一个空消息 */ public AjaxResult(){} /** * 初始化一个新创建的AjaxResult对象 * @param type 状态类型 * @param msg 返回内容 */ public AjaxResult(Type type,String msg){ super.put(CODE_TAG,type.value); super.put(MSG_TAG,msg); } /** * 初始化一个新创建的AjaxResult对象 * @param type 转台类型 * @param msg 返回内容 * @param data 数据对象 */ public AjaxResult(Type type,String msg,Object data){ super.put(CODE_TAG,type.value); super.put(MSG_TAG,msg); super.put(DATA_TAG,data); } /** * 返回成功消息 */ public static AjaxResult success(){ return AjaxResult.success("操作成功"); } /** * 返回成功消息 */ public static AjaxResult success(String msg){ return AjaxResult.success(msg, null); } /** * 返回成功消息 */ public static AjaxResult success(String msg,Object data){ return new AjaxResult(Type.SUCCESS,msg,data); } /** * 返回失败消息 */ public static AjaxResult fail(){ return AjaxResult.fail("操作失败"); } /** * 返回失败消息 */ public static AjaxResult fail(String msg){ return AjaxResult.fail(msg,null); } /** * 返回失败消息 */ public static AjaxResult fail(String msg,Object data){ return new AjaxResult(Type.FAIL,msg,data); } /** * 返回警告消息 */ public static AjaxResult warn(String msg,Object data){ return new AjaxResult(Type.WARN,msg,data); } /** * 返回错误消息 */ public static AjaxResult error(){ return AjaxResult.error("操作错误"); } /** * 返回错误消息 */ public static AjaxResult error(String msg){ return AjaxResult.error(msg,null); } /** * 返回错误消息 */ public static AjaxResult error(String msg,Object data){ return new AjaxResult(Type.ERROR,msg,data); } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } }
第五步:使用Token
import com.alibaba.fastjson.JSONObject; import com.one.smile.dream.entity.User; import com.one.smile.dream.service.IUserService; import com.one.smile.dream.util.AjaxResult; import com.one.smile.dream.util.JwtUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import java.util.Map; @Controller public class LoginController { @Autowired private IUserService userService; @PostMapping("loginToken") @ResponseBody public AjaxResult login(@RequestBody Map<String,String> map){ String loginName = map.get("loginName"); String password = map.get("passWord"); //身份验证 boolean isSuccess = userService.checkUser(loginName,password); if(isSuccess){ //模拟数据库查询 User user = userService.getUser(loginName); if(user != null){ //返回token String token = JwtUtil.sign(loginName,password); if(token != null){ return AjaxResult.success("成功",token); } } } return AjaxResult.fail(); } @PostMapping("getUser") @ResponseBody public AjaxResult getUserInfo(HttpServletRequest request,@RequestBody Map<String,String> map){ String loginName = map.get("loginName"); String token = request.getHeader("token"); boolean verity = JwtUtil.verity(token); //token验证 if(verity){ User user = userService.getUser(loginName); if(user != null){ return AjaxResult.success("成功", JSONObject.toJSONString(user)); } } return AjaxResult.fail(); } }
import com.one.smile.dream.entity.User; public interface IUserService { /** * 校验用户信息 * @param username * @param passWord * @return */ boolean checkUser(String username,String passWord); /** * 查询用户信息 * @param loginName * @return */ User getUser(String loginName); }
import com.one.smile.dream.entity.User; import com.one.smile.dream.service.IUserService; import org.springframework.stereotype.Service; @Service("userService") public class UserServiceImpl implements IUserService { @Override public boolean checkUser(String username, String password) { return true; } @Override public User getUser(String loginName) { User user = new User(); user.setId(111); user.setUser_code("李四"); user.setUser_pass("123"); user.setS_id("11123"); return user; } }