jwt登录代码实现

1.先引入jwt的pom.xml

      
        
            io.jsonwebtoken
            jjwt
            0.7.0
        

2.实现jwt代码

2.1 实现代码

 private UserTokenVO generateTokenAndCache(JwtUserParam jwtUserParam) {
        String tokenUuid = UUID.randomUUID().toString().replaceAll("-", "")
                .concat(String.valueOf(System.currentTimeMillis()));
        jwtUserParam.setTokenUuid(tokenUuid);

        long now = System.currentTimeMillis();
        long accessTokenTtlMillis = 1000L * Integer.valueOf(accessTokenExpiresSecond);
        String accessToken = JwtHelper.createJWT(jwtUserParam, accessTokenTtlMillis, jwtSecret);
        long refreshTokenTtlMills = 1000L * Integer.valueOf(refreshTokenExpiresSecond);
        String refreshToken = JwtHelper.createJWT(jwtUserParam, refreshTokenTtlMills, jwtSecret);

        //缓存token
        UserTokenVO userTokenVO = ObjectCopyUtil.bean2Bean(jwtUserParam, UserTokenVO.class);
        userTokenVO.setUserAccount(jwtUserParam.getLoginName());
        userTokenVO.setAccessToken(accessToken);
        userTokenVO.setRefreshToken(refreshToken);
        userTokenVO.setTokenExpireTime(new Date(now + accessTokenTtlMillis));
        userTokenVO.setRefreshExpireTime(new Date(now + refreshTokenTtlMills));

        //保存用户令牌信息
        UserToken userToken = ObjectCopyUtil.bean2Bean(userTokenVO, UserToken.class);
        userToken.setSystemType(jwtUserParam.getSysType());
        userToken.setCreateTime(Date.from(Instant.now()));
        userToken.setCreatePeople(userToken.getUserAccount());
        userTokenService.save(userToken);

        try {
            userTokenUtil.setUserTokenById(tokenUuid, JSON.toJSONString(userTokenVO), Integer.valueOf(refreshTokenExpiresSecond));
        } catch (Exception e) {
            log.error("设置用户令牌信息到缓存发生异常", e);
            return null;
        }
        return userTokenVO;
    }
    /**
     * 设置用户token到缓存
     *
     * @param tokenUuid tokenUuid
     * @param data      存储数据
     * @param eTime     过期时间 秒
     * @throws Exception
     */
    public void setUserTokenById(String tokenUuid, String data, int eTime) {
        jedisClient.set(CommonConstants.CACHE_USER_TOKEN_KEY + tokenUuid, eTime, data);
    }

public class JwtUserParam implements Serializable {
    private Long userId;
    private Long parentCorpId;
    private Long corpId;
    private String corpName;
    private String loginName;
    private String userName;
    private String nickName;
    private String tokenUuid;
    private Integer mgtType;
    private String deviceId;
    private String sysType;
    private String objType;
    private String role;
    private Long appKey;
}

你可能感兴趣的:(jwt登录代码实现)