TokenController.java 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package com.ruoyi.auth.controller;
  2. import java.util.Map;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.http.HttpHeaders;
  5. import org.springframework.security.oauth2.common.OAuth2AccessToken;
  6. import org.springframework.security.oauth2.common.OAuth2RefreshToken;
  7. import org.springframework.security.oauth2.provider.token.TokenStore;
  8. import org.springframework.web.bind.annotation.DeleteMapping;
  9. import org.springframework.web.bind.annotation.RequestHeader;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RestController;
  12. import com.ruoyi.common.core.constant.Constants;
  13. import com.ruoyi.common.core.constant.SecurityConstants;
  14. import com.ruoyi.common.core.domain.R;
  15. import com.ruoyi.common.core.utils.StringUtils;
  16. import com.ruoyi.system.api.RemoteLogService;
  17. /**
  18. * token 控制
  19. *
  20. * @author ruoyi
  21. */
  22. @RestController
  23. @RequestMapping("/token")
  24. public class TokenController
  25. {
  26. @Autowired
  27. private TokenStore tokenStore;
  28. @Autowired
  29. private RemoteLogService remoteLogService;
  30. @DeleteMapping("/logout")
  31. public R<?> logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader)
  32. {
  33. if (StringUtils.isEmpty(authHeader))
  34. {
  35. return R.ok();
  36. }
  37. String tokenValue = authHeader.replace(OAuth2AccessToken.BEARER_TYPE, StringUtils.EMPTY).trim();
  38. OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
  39. if (accessToken == null || StringUtils.isEmpty(accessToken.getValue()))
  40. {
  41. return R.ok();
  42. }
  43. // 清空 access token
  44. tokenStore.removeAccessToken(accessToken);
  45. // 清空 refresh token
  46. OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
  47. tokenStore.removeRefreshToken(refreshToken);
  48. Map<String, ?> map = accessToken.getAdditionalInformation();
  49. if (map.containsKey(SecurityConstants.DETAILS_USERNAME))
  50. {
  51. String username = (String) map.get(SecurityConstants.DETAILS_USERNAME);
  52. // 记录用户退出日志
  53. remoteLogService.saveLogininfor(username, Constants.LOGOUT, "退出成功");
  54. }
  55. return R.ok();
  56. }
  57. }