SecurityService.java 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package com.bofeng.service;
  2. import com.bofeng.JwtHelper;
  3. import com.bofeng.entity.User;
  4. import com.yvan.platform.Conv;
  5. import lombok.val;
  6. import org.apache.shiro.authc.AuthenticationException;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.beans.factory.annotation.Value;
  9. import org.springframework.data.redis.core.StringRedisTemplate;
  10. import org.springframework.stereotype.Service;
  11. import java.util.concurrent.TimeUnit;
  12. @Service
  13. public class SecurityService {
  14. private static final int EXPIRE_MINUTES = 24 * 60;
  15. @Value("${secret:jztd}")
  16. private String secret = "jztd";
  17. @Value("${salt:jztd2}")
  18. private String salt = "jztd2";
  19. @Value("${token_time_minutes:30}")
  20. public int tokenTimeMinutes = 30;
  21. @Value("${token_time_minutes_mobile:30}")
  22. public int tokenTimeMinutesMobile = 30;
  23. @Autowired
  24. private StringRedisTemplate stringRedisTemplate;
  25. public void setVersion(String userId, String tokenVersion) {
  26. val key = "token:" + userId;
  27. stringRedisTemplate.opsForValue().set(key, tokenVersion);
  28. }
  29. public void setAccountUserId(Long accountId, Long userId) {
  30. val key = "account_user:" + accountId;
  31. stringRedisTemplate.opsForValue().set(key, userId.toString(), EXPIRE_MINUTES, TimeUnit.MINUTES);
  32. }
  33. public void setAccountUserId(Long userId) {
  34. val key = "account_user:" + userId;
  35. stringRedisTemplate.opsForValue().set(key, userId.toString(), EXPIRE_MINUTES, TimeUnit.MINUTES);
  36. }
  37. public String getVersion(Long userId) {
  38. val key = "token:" + userId;
  39. return stringRedisTemplate.opsForValue().get(key);
  40. }
  41. public String createPassword(User user, String loginPwd) {
  42. return loginPwd;
  43. }
  44. public String createJwt(User user, boolean isMobile) {
  45. return JwtHelper.sign(user.getUserId(),
  46. user.getUserType(),
  47. user.getStaffName(),
  48. secret,
  49. isMobile ? tokenTimeMinutesMobile : tokenTimeMinutes);
  50. }
  51. public void verify(String jwtToken) {
  52. final Long userId = JwtHelper.getUserId(jwtToken);
  53. String tokenVersion = getVersion(userId);
  54. if (!JwtHelper.verify(jwtToken, userId, tokenVersion, secret)) {
  55. throw new AuthenticationException("tokenVersion expire!");
  56. }
  57. }
  58. }