session原理(适用于单体的身份效验)
Http 无状态,有会话
- 无状态是指,请求之间相互独立,第一次请求的数据,第二次请求不能重用
- 有会话是指,客户端和服务端都有相应的技术,可以暂存数据,让数据在请求见共享
服务端使用了session技术来暂存数据
存
GET /s1?name=zhang HTTP/1.1
Host: localhost
取
GET /s2 HTTP/1.1
Host: localhost
Cookie: JSESSIONID=BF219FEFB6FF6960ODA2537CDDED6C393
@RequestMapping("/s1")
@ResponseBody
public String s1(HttpSession session, String name) {
session.setAttribute("name", name);
return "数据已存储";
}
@RequestMapping("/s2")
@ResponseBody
public String s2(HttpSession session) {
return "取出数据" + session.getAttribute("name");
}
jwt原理(适用于分布式的登录校验)
生成token
GET /j1?name=zhang&pass=123 HTTP/1.1
Host: 1ocaThost
校验token
GET /j2 HTTP/1.1
Host: localhost
Authorization:
eyjhbGcioiJIuzIlNij9.eyJzdwIioijhzGlpbij9.G4Xp74sX4dEC-KIwhK2kRmj1w157nSAROOBMspQ-1o8
@RequestMapping("/j1")
@ResponseBody
public String j1(String name, String pass) {
Calendar instance = Calendar.getInstance();
//令牌过期时间 20s
instance.add(Calendar.SECOND,20);
if ("zhang".equals(name) && "123".equals(pass)) {
String token = JWT.create()
.withClaim("name", name)
.withClaim("pass", pass)
.withExpiresAt(instance.getTime())
.sign(Algorithm.HMAC256("BUTU"));
return "验证身份通过"+token;
}else {
return "验证身份失败";
}
}
@RequestMapping("/j1")
@ResponseBody
public String j2(@RequestHeader String authorization) {
//通过签名生成验证对象
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("BUTU")).build();
DecodedJWT verify = jwtVerifier.verify(authorization);
return "name:"+verify.getClaim("name")+"\n"+"pass:"+verify.getClaim("pass");
}
标签:Java,name,前端,Day05,Host,session,pass,return,String
From: https://blog.51cto.com/u_15806490/8305434