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