赞
踩
/** * 缓存token * @param userId * @param token */ public void setTokenUser(String userId, String token) { // 缓存token /** token失效时间 18000 = 5小时 7200 = 2小时 3600 = 1小时 1800 = 半小时 900 = 15分钟 60 = 1分钟*/ MapCache.single().set("tokenUser" + userId, token, 18000); // 两小时过期 MapCache.single().set(token, getSysUser(), 18000); // 两小时过期 } /** * 验证token信息 * * @return User */ public SysUser analyticalUser() { String token = null; try { token = getRequest().getHeader("accessToken"); } catch (NoSuchMessageException e) { /** token失效状态 */ throw new UserTokenInvalidException("10000", null, "无认证信息,请先登录"); } if (token == null) { /** token失效状态 */ throw new UserTokenInvalidException("10000", null, "无认证信息,请先登录"); } SysUser user = MapCache.single().get(token); if (user == null) { /** token失效状态 */ throw new UserTokenInvalidException("10000", null, "认证失效,请先登录"); } /** * token缓存常量 */ String tokenVerify = MapCache.single().get("tokenUser" + user.getUserId()); System.out.println(tokenVerify); if (!tokenVerify.equals(token)) { /** token失效状态 */ throw new UserTokenInvalidException("10000", null, "登录失效,请先登录"); } MapCache.single().set("tokenUser" + user.getUserId(), token, 18000); // 两小时过期 MapCache.single().set(token, user, 18000); return user; }
/** * 用户对象 sys_user */ public class SysUser extends BaseEntity { private static final long serialVersionUID = 1L; /** 用户ID */ @Excel(name = "用户序号", cellType = ColumnType.NUMERIC, prompt = "用户编号") private Long userId; /** 部门ID */ @Excel(name = "部门编号", type = Type.IMPORT) private Long deptId; /** 角色ID */ private Long roleId; /** 登录名称 */ @Excel(name = "登录名称") private String loginName; /** 用户名称 */ @Excel(name = "用户名称") private String userName; /** 密码 */ private String password; /** 盐加密 */ private String salt; /** 帐号状态(0正常 1停用) */ @Excel(name = "帐号状态", readConverterExp = "0=正常,1=停用") private String status; /** 删除标志(0代表存在 2代表删除) */ private String delFlag; /** 密码最后更新时间 */ private Date pwdUpdateDate; public SysUser() { } public SysUser(Long userId) { this.userId = userId; } }
import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Map 缓存实现 */ public class MapCache { /** * 默认存储1024个缓存 */ private static final int DEFAULT_CACHES = 1024; private static final MapCache INS = new MapCache(); public static MapCache single() { return INS; } /** * 缓存容器 */ private final Map<String, CacheObject> cachePool; public MapCache() { this(DEFAULT_CACHES); } public MapCache(int cacheCount) { cachePool = new ConcurrentHashMap<>(cacheCount); } /** * 读取一个缓存 * * @param key 缓存key * @param <T> * @return */ public <T> T get(String key) { CacheObject cacheObject = cachePool.get(key); if (null != cacheObject) { long cur = System.currentTimeMillis() / 1000; if (cacheObject.getExpired() <= 0 || cacheObject.getExpired() > cur) { Object result = cacheObject.getValue(); return (T) result; } } return null; } /** * 读取一个hash类型缓存 * * @param key 缓存key * @param field 缓存field * @param <T> * @return */ public <T> T hget(String key, String field) { key = key + ":" + field; return this.get(key); } /** * 设置一个缓存 * * @param key 缓存key * @param value 缓存value */ public void set(String key, Object value) { this.set(key, value, -1); } /** * 设置一个缓存并带过期时间 * * @param key 缓存key * @param value 缓存value * @param expired 过期时间,单位为秒 */ public void set(String key, Object value, long expired) { expired = expired > 0 ? System.currentTimeMillis() / 1000 + expired : expired; CacheObject cacheObject = new CacheObject(key, value, expired); cachePool.put(key, cacheObject); } /** * 设置一个hash缓存 * * @param key 缓存key * @param field 缓存field * @param value 缓存value */ public void hset(String key, String field, Object value) { this.hset(key, field, value, -1); } /** * 设置一个hash缓存并带过期时间 * * @param key 缓存key * @param field 缓存field * @param value 缓存value * @param expired 过期时间,单位为秒 */ public void hset(String key, String field, Object value, long expired) { key = key + ":" + field; expired = expired > 0 ? System.currentTimeMillis() / 1000 + expired : expired; CacheObject cacheObject = new CacheObject(key, value, expired); cachePool.put(key, cacheObject); } /** * 根据key删除缓存 * * @param key 缓存key */ public void del(String key) { cachePool.remove(key); } /** * 根据key和field删除缓存 * * @param key 缓存key * @param field 缓存field */ public void hdel(String key, String field) { key = key + ":" + field; this.del(key); } /** * 清空缓存 */ public void clean() { cachePool.clear(); } static class CacheObject { private final String key; private final Object value; private final long expired; public CacheObject(String key, Object value, long expired) { this.key = key; this.value = value; this.expired = expired; } public String getKey() { return key; } public Object getValue() { return value; } public long getExpired() { return expired; } } }
import com.common.exception.base.BaseException; /** * 用户token相关错误 */ public class UserTokenInvalidException extends BaseException { private static final long serialVersionUID = 1L; public UserTokenInvalidException(String code, Object[] args, String message) { super("user token invalid", code, args, message); } }
/** * shiro 工具类 */ public class ShiroUtils { public static Subject getSubject() { return SecurityUtils.getSubject(); } public static Session getSession() { return SecurityUtils.getSubject().getSession(); } public static void logout() { getSubject().logout(); } public static SysUser getSysUser() { SysUser user = null; Object obj = getSubject().getPrincipal(); if (StringUtils.isNotNull(obj)) { user = new SysUser(); BeanUtils.copyBeanProp(user, obj); } return user; } public static void setSysUser(SysUser user) { Subject subject = getSubject(); PrincipalCollection principalCollection = subject.getPrincipals(); String realmName = principalCollection.getRealmNames().iterator().next(); PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName); // 重新加载Principal subject.runAs(newPrincipalCollection); } public static Long getUserId() { return getSysUser().getUserId().longValue(); } public static String getLoginName() { return getSysUser().getLoginName(); } public static String getIp() { return getSubject().getSession().getHost(); } public static String getSessionId() { return String.valueOf(getSubject().getSession().getId()); } /** * 生成随机盐 */ public static String randomSalt() { // 一个Byte占两个字节,此处生成的3字节,字符串长度为6 SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator(); String hex = secureRandom.nextBytes(3).toHex(); return hex; } }
/** * pad端登录 * @param username 账号 * @param password 密码 */ @PostMapping("/login") @ResponseBody public AjaxResult login(@NotNull(message = "用户不能为空!")String username, @NotNull(message = "密码不能为空!")String password , HttpServletRequest request) throws IOException { System.out.println("pad登录>>>>userName>>>"+username+">>>password>>>"+password); UsernamePasswordToken token = new UsernamePasswordToken(username, password, false); Subject subject = SecurityUtils.getSubject(); try { //已有登录验证 subject.login(token); //返回的实体 loginDto dto = new loginDto(); dto.setUserId(getUserId().toString());//用户ID dto.setToken(UUID.randomUUID().toString());//返回 System.out.println("【登录获取token】{}"+dto.getToken()); //缓存token setTokenUser(dto.getUserId(),dto.getToken()); return AjaxResult.success(dto); } catch (AuthenticationException e) { String msg = "登录名或密码错误"; return error(msg); } } @PostMapping("/getUser") @ResponseBody public AjaxResult getUser(){ System.out.println("【解析访问用户信息】"); SysUser user = analyticalUser(); return AjaxResult.success(user); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。