zoukankan      html  css  js  c++  java
  • JWT使用记录

    工具类

    KeyHelper

    //生产公钥和私钥
    //publicKeyFilename为公钥文件及路径
    //privateKeyFilename为私钥文件及路径
    public static void generateKey(String publicKeyFilename,String privateKeyFilename,String password) throws IOException, NoSuchAlgorithmException 
     public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
            generateKey("d:/pub.key","d:/pri.key","**2*&!223k");
        }

    执行后会在d盘下创建出公钥和私钥

    JWTHelper

     /**
         * 密钥加密token
         * @param jwtInfo 包含有用户名称和id的用户对象
         * @param priKeyPath  私钥地址
         * @param expire 过期时间
         * @return token 生成的token
         * @throws Exception
         */
        public static String generateToken(IJWTInfo jwtInfo, String priKeyPath, int expire) throws Exception {
            String compactJws = Jwts.builder()
                    .setSubject(jwtInfo.getUniqueName())
                    .claim(CommonConstants.JWT_KEY_USER_ID, jwtInfo.getId())
                    .claim(CommonConstants.JWT_KEY_NAME, jwtInfo.getName())
                    .setExpiration(DateTime.now().plusSeconds(expire).toDate())
                    .signWith(SignatureAlgorithm.RS256, KeyHelper.getPrivateKey(priKeyPath))
                    .compact();
            return compactJws;
        }
     /**
         * 获取token中的用户信息
         * @param token  
         * @param pubKeyPath 公钥路径
         * @return 返回包含用户信息的对象
         * @throws Exception
         */
        public static IJWTInfo getInfoFromToken(String token, String pubKeyPath) throws Exception {
            Jws<Claims> claimsJws = parserToken(token, pubKeyPath);
            Claims body = claimsJws.getBody();
            return new JWTInfo(body.getSubject(), StringHelper.getObjectValue(body.get(CommonConstants.JWT_KEY_USER_ID)), StringHelper.getObjectValue(body.get(CommonConstants.JWT_KEY_NAME)));
        }
    public static void main(String args[]){
            //创建测试对象 
            IJWTInfo info=new JWTInfo("a","b","c");
            try {
                //获取token值
                String token=generateToken(info,"d:/pri.key",60);
                System.out.println(token);
                //根据token及公钥路径获取原始的用户对象
                IJWTInfo in=getInfoFromToken(token,"d:/pub.key");
                //打印用户对象中的数据值
                System.out.println(in.getUniqueName()+"  "+in.getId()+"  "+in.getName());
            } catch (Exception e) {
            }
        }
    /**
     * 网关过滤器
     * 1 根据用户名称和id验证
     * 2 根据clientId和clientSecret验证
     * 如果以上2个任何一个没有验证通过,网关返回错误信息,不让访问
     * @author Administrator
     *
     */
    @Component
    public class AccessFilter extends ZuulFilter{}
  • 相关阅读:
    VS中的DataPager分页
    获取select标签选中的值
    JS判断包括IE11在内的IE浏览器
    几款jQuery右键菜单插件
    java day2
    java day1
    转换成(大)小写字母
    模态框扩展
    自定义动画,点赞
    反选
  • 原文地址:https://www.cnblogs.com/luleiitlife/p/8544966.html
Copyright © 2011-2022 走看看