-
Notifications
You must be signed in to change notification settings - Fork 649
/
Jwt.java
64 lines (54 loc) · 1.93 KB
/
Jwt.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package org.joychou.controller;
import lombok.extern.slf4j.Slf4j;
import org.joychou.util.CookieUtils;
import org.joychou.util.JwtUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
*/
@Slf4j
@RestController
@RequestMapping("/jwt")
public class Jwt {
private static final String COOKIE_NAME = "USER_COOKIE";
/**
* http://localhost:8080/jwt/createToken
* Create jwt token and set token to cookies.
*
* @author JoyChou 2022-09-20
*/
@GetMapping("/createToken")
public String createToken(HttpServletResponse response, HttpServletRequest request) {
String loginUser = request.getUserPrincipal().getName();
log.info("Current login user is " + loginUser);
if (!CookieUtils.deleteCookie(response, COOKIE_NAME)){
return String.format("%s cookie delete failed", COOKIE_NAME);
}
String token = JwtUtils.generateTokenByJavaJwt(loginUser);
Cookie cookie = new Cookie(COOKIE_NAME, token);
cookie.setMaxAge(86400); // 1 DAY
cookie.setPath("/");
cookie.setSecure(true);
response.addCookie(cookie);
return "Add jwt token cookie successfully. Cookie name is USER_COOKIE";
}
/**
* http://localhost:8080/jwt/getName
* Get nickname from USER_COOKIE
*
* @author JoyChou 2022-09-20
* @param user_cookie cookie
* @return nickname
*/
@GetMapping("/getName")
public String getNickname(@CookieValue(COOKIE_NAME) String user_cookie) {
String nickname = JwtUtils.getNicknameByJavaJwt(user_cookie);
return "Current jwt user is " + nickname;
}
}