pom.xml
<dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.10.3</version> </dependency>
TokenUtil : 生成token , 解析token
public class TokenUtil { //token到期时间60s private static final long EXPIRE_TIME= 600*1000; //密钥盐 private static final String TOKEN_SECRET="123456qwertyuiop789"; /** * 创建一个token * @param customerTokenDTO * @return 生成的token中不带有过期时间,token的过期时间由redis进行管理 */ public static String sign(CustomerTokenDTO customerTokenDTO){ System.out.println("sign customer:" + customerTokenDTO); String token=null; try { Map<String, Object> header = new HashMap<>(2); header.put("Type", "Jwt"); header.put("alg", "HS256"); token = JWT.create() .withHeader(header) .withClaim("token", JSONObject.toJSONString(customerTokenDTO))//存放数据 .sign(Algorithm.HMAC256(TOKEN_SECRET)); } catch (IllegalArgumentException| JWTCreationException je) { je.printStackTrace(); } return token; } /** * 对token进行验证 * @param token * @return */ public static CustomerTokenDTO parseToken(String token){ Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET); JWTVerifier verifier = JWT.require(algorithm).build(); DecodedJWT decodedJWT = verifier.verify(token); String tokenInfo = decodedJWT.getClaim("token").asString(); CustomerTokenDTO customerTokenDTO = JSON.parseObject(tokenInfo, CustomerTokenDTO.class); System.out.println("获得的token中的信息是:" + customerTokenDTO); return customerTokenDTO; } }
登录用户的信息封装CustomerTokenDTO
/** * CustomerTokenDTO 中不带有敏感信息,如 password字段不会出现在token中 */ public class CustomerTokenDTO { private Integer custId; private String custName; // 构造函数 // get set }
1. 登录请求
客户端 服务器 用户名密码 ----------<1>登录----------> (2)验证码用户信息(id,name) <------- (token)响应---------- (3)生成token <4>存储token 到localStorage localStorage.setItem("token",token);
2. 收藏/查看我的订单
需要用到当前登录用户的信息
客户端 服务器 -------------------request ----------------------> 1. var token =localStorage.getItem("token"); 4. String token = request.getHeader("token"); 2.请求 5. CustomerTokenDTO dto= TokenUtil.parseToken(token); 6. Integer custId = dto.getCustId(); 3.headers: {'token': token}, 7. String custName = dto.getCustName();
3. 登录请求代码:
<script src="js/jquery-3.3.1.min.js" ></script> <form method="post"> 用户名:<input type="text" class="custName" name="custName"><br> 密码:<input type="password" class="custPassword" name="custPassword"><br> <input type="button" class="loginBtn" value="登录"> </form> <script> $(".loginBtn").click(function (){ $.ajax({ type:"post", url:"customer/login", data:{ custName:$(".custName").val(), custPassword:$(".custPassword").val() }, success:function (result){ console.log("result:" + result); //保存信息到本地,里面都 token var token = JSON.stringify(result.data); console.log("token:" + token); localStorage.setItem("token",token); // window.location.href = "index.jsp"; } }) }) </script>
CustomerController
//登录 @PostMapping("login") @ResponseBody public ServerResponse login(Customer customer, HttpServletRequest request, HttpServletResponse response){ ServerResponse result = customerService.login(customer); System.out.println("controller login response:" + result); if(result.getCode() ==200){ String token = (String) result.getData(); System.out.println("customer controller 登录成功"); } return result; }
4. 其他请求携带token信息到服务器
<script src="js/jquery-3.3.1.min.js" ></script> <a href="javascript:void(0)" class="btn1">ajax异步请求,带有token</a> <script> $(".btn1").click(function (){ var tokenStr = localStorage.getItem("token"); var token = JSON.parse(tokenStr); console.log(token); $.ajax({ type:"get", url:"test1", headers: {'token': token}, success:function (data){ console.log(data) } }) }) </script>
@GetMapping("/test1") public String test1(HttpServletRequest request){ //从请求头部获得token String token = request.getHeader("token"); //get token System.out.println(token); //解析token ,获得登录用户的信息 Integer customerId = TokenUtil.parseToken(token).getCustId(); System.out.println("test1 customer Id = " + customerId); return "test1 get token ok"; }