package com.tiesheng.util.config; import cn.hutool.core.map.MapUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.extra.servlet.ServletUtil; import cn.hutool.json.JSONUtil; import cn.hutool.jwt.JWT; import cn.hutool.jwt.JWTValidator; import com.tiesheng.util.exception.ApiException; import com.tiesheng.util.pojos.TokenBean; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import javax.servlet.http.HttpServletRequest; import java.util.Map; /** * @author hao */ @Configuration @ConfigurationProperties("tiesheng.token") public class TsTokenConfig { /** * 用户登录的KEY */ public static String CACHE_REQUEST_LOGIN_KEY = "CACHE:LOGIN:{}"; /** * token常量 */ public static final String TOKEN_KEY = "token"; private Map testMap = MapUtil.newHashMap(); private String encryptKey = "%kIp9frQCu"; private Integer expireHours = 48; private String[] ignorePaths; private boolean validLoginSign = false; /** * 验证token * * @param token * @return */ public TokenBean isTestToken(String token) { if (testMap == null) { return null; } return testMap.get(token); } /** * 验证token * * @param thrExp * @return */ public TokenBean validToken(HttpServletRequest request, boolean thrExp) { String token = ServletUtil.getHeader(request, TOKEN_KEY, "utf-8"); return validToken(token, thrExp); } /** * 验证token * * @return */ public TokenBean validToken(String token, boolean thrExp) { TokenBean tokenBean = isTestToken(token); if (tokenBean != null) { return tokenBean; } try { JWT decode = JWT.of(token); JWTValidator.of(decode).validateDate(); tokenBean = JSONUtil.toBean(decode.getPayloads(), TokenBean.class); } catch (Exception ignored) { } if ((tokenBean == null || StrUtil.isEmpty(tokenBean.getId())) && thrExp) { throw new ApiException(StrUtil.isEmpty(token) ? 110 : 112, StrUtil.isEmpty(token) ? "请先登录" : "登录过期,请重新登陆"); } if (tokenBean == null) { tokenBean = new TokenBean(); tokenBean.setId(""); } return tokenBean; } /////////////////////////////////////////////////////////////////////////// // setter\getter /////////////////////////////////////////////////////////////////////////// public Map getTestMap() { return testMap; } public void setTestMap(Map testMap) { this.testMap = testMap; } public String getEncryptKey() { return encryptKey; } public void setEncryptKey(String encryptKey) { this.encryptKey = encryptKey; } public Integer getExpireHours() { return expireHours; } public void setExpireHours(Integer expireHours) { this.expireHours = expireHours; } public String[] getIgnorePaths() { return ignorePaths; } public void setIgnorePaths(String[] ignorePaths) { this.ignorePaths = ignorePaths; } public boolean isValidLoginSign() { return validLoginSign; } public void setValidLoginSign(boolean validLoginSign) { this.validLoginSign = validLoginSign; } }