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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
| package top.yuan67.webapp.controller;
import cn.hutool.jwt.JWT; import cn.hutool.jwt.JWTUtil; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONObject; import io.netty.util.internal.StringUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.ProviderManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.web.bind.annotation.*; import top.yuan67.webapp.constant.AuthorizationConstant; import top.yuan67.webapp.entity.BaseAdmin; import top.yuan67.webapp.entity.BaseUser; import top.yuan67.webapp.exception.AccessTokenException; import top.yuan67.webapp.service.BaseAdminService; import top.yuan67.webapp.service.BaseUserService; import top.yuan67.webapp.util.HTTPResponse; import top.yuan67.webapp.util.MessageUtil; import top.yuan67.webapp.util.TokenUtil; import top.yuan67.webapp.vo.LoginAdminVO;
import javax.annotation.Resource; import java.util.LinkedHashMap; import java.util.Map;
@RestController @RequestMapping("/oauth") public class BaseTokenController { public static final Logger log = LoggerFactory.getLogger(BaseTokenController.class); @Resource private RedisTemplate redisTemplate; @Resource private TokenUtil tokenUtil; @Resource private BaseAdminService adminService; @Resource private BaseUserService userService; @Resource private BCryptPasswordEncoder encoder;
@PostMapping("/loginAdmin") public HTTPResponse loginAdmin(@RequestBody LoginAdminVO login){ log.info("用户登录:{}", login); Authentication authentication; try { DaoAuthenticationProvider adminProvider = new DaoAuthenticationProvider(); adminProvider.setUserDetailsService(adminService); adminProvider.setPasswordEncoder(encoder); ProviderManager manager = new ProviderManager(adminProvider); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(login.getUsername(), login.getPassword()); authentication = manager.authenticate(token); } catch (Exception e) { return exception(login, e); } SecurityContextHolder.getContext() .setAuthentication(UsernamePasswordAuthenticationToken .authenticated(authentication.getPrincipal(), null, authentication.getAuthorities())); return HTTPResponse.ok("登录成功", tokenUtil.login((BaseAdmin) authentication.getPrincipal())); }
@PostMapping("/loginUser") public HTTPResponse loginUser(@RequestBody LoginAdminVO login) throws AccessTokenException { Authentication authentication; try{ DaoAuthenticationProvider userProvider = new DaoAuthenticationProvider(); userProvider.setUserDetailsService(userService); userProvider.setPasswordEncoder(encoder); ProviderManager manager = new ProviderManager(userProvider); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(login.getUsername(), login.getPassword()); authentication = manager.authenticate(token); }catch (Exception e){ return exception(login, e); } SecurityContextHolder.getContext() .setAuthentication(UsernamePasswordAuthenticationToken .authenticated(authentication.getPrincipal(), null, authentication.getAuthorities())); return HTTPResponse.ok("登录成功", tokenUtil.login((BaseUser)authentication.getPrincipal())); } @GetMapping("/findCurrentUserInfo") public Map<String, Object> findCurrentUserInfo(){ String token = redisTemplate.opsForHash() .get(tokenUtil.accessTokenKey(), AuthorizationConstant.USER_INFO).toString(); return JSONObject.parseObject(token, Map.class); }
@PostMapping("/refreshToken/admin") public Map<String, Object> refreshTokenAdmin(String refreshToken) { return refreshToken(refreshToken, "admin"); } @PostMapping("/refreshToken/user") public Map<String, Object> refreshTokenUser(String refreshToken) { return refreshToken(refreshToken, "user"); } private Map<String, Object> refreshToken(String refreshToken, String type){ log.info("refreshToken:{}", refreshToken); Map<String, Object> map = new LinkedHashMap<>(); if (tokenUtil.isNotEmpty(refreshToken)) { boolean verify; try { verify = JWTUtil.verify(refreshToken, AuthorizationConstant.REFRESH_TOKEN_SECRET.getBytes()); log.info("verify:{}", verify); } catch (Exception e) { log.error("token无法解析:{}", e); throw new RuntimeException(MessageUtil.get("令牌解析异常")); } if (verify) { try { JWT jwt = JWTUtil.parseToken(refreshToken); String key = tokenUtil.refreshTokenKey(refreshToken); boolean b = redisTemplate.hasKey(key); if(!b){ map.put("status", 500); map.put("message", MessageUtil.get("刷新令牌过期")); return map; } String header = jwt.getHeader(AuthorizationConstant.HEADER).toString(); if (!header.equalsIgnoreCase(AuthorizationConstant.HEADER_REFRESH_TOKEN)) { map.put("status", 500); map.put("message", MessageUtil.get("令牌解析异常")); return map; }
String redisRefreshToken = redisTemplate.opsForHash().get(key, AuthorizationConstant.TOKEN).toString(); String redisAdmin = redisTemplate.opsForHash().get(key, AuthorizationConstant.USER_INFO).toString(); long exp = redisTemplate.getExpire(key); long now = System.currentTimeMillis() / 1000; log.info("key:{}, exp:{}, now:{}, cha:{}", key, exp, now, exp - now); if (exp - now < 0) { log.info("刷新令牌彻底过期exp:{}, now:{}, exp - now={}", exp, now, (exp - now)); map.put("status", 500); map.put("message", MessageUtil.get("令牌过期!请重新登录")); return map; } if (!redisRefreshToken.equals(refreshToken)) { map.put("status", 500); map.put("message", MessageUtil.get("令牌解析异常")); return map; } log.info("刷新令牌还未过期,但距离过期还有{}分钟,所以刷新token", (exp - now) / 60); if(type.equalsIgnoreCase("user")){ BaseUser user = JSON.parseObject(redisAdmin, BaseUser.class); return tokenUtil.login(user); } if(type.equalsIgnoreCase("admin")){ BaseAdmin admin = JSON.parseObject(redisAdmin, BaseAdmin.class); return tokenUtil.login(admin); } } catch (Exception e) { log.warn("用户身份过期!:{}", e); map.put("status", 500); map.put("message", MessageUtil.get("用户身份过期!请重新登录")); map.put("data", MessageUtil.get("用户身份不存在")); return map; } }else{ map.put("status", 500); map.put("message", MessageUtil.get("令牌解析异常")); return map; } } map.put("status", 500); map.put("message", MessageUtil.get("关键参数不能为空")); return map; } private HTTPResponse exception(LoginAdminVO login, Exception e) { if (e instanceof BadCredentialsException) { log.error("e====={}", e); log.info("用户名或密码错误:username:{}, password:{}", login.getUsername(), login.getPassword()); return HTTPResponse.error("用户名或密码错误"); } return HTTPResponse.error(e.getMessage()); } }
|