zoukankan      html  css  js  c++  java
  • springcloud安全控制token的创建与解析

    import io.jsonwebtoken.Claims;
    import io.jsonwebtoken.Jwts;
    import io.jsonwebtoken.SignatureAlgorithm;
    import org.springframework.stereotype.Service;
    
    import javax.crypto.spec.SecretKeySpec;
    import java.security.Key;
    import java.util.Base64;
    import java.util.UUID;
    
    /**
     * Create by liping on 2018/9/25
     */
    @Service
    public class JWTService {
        private static final String encodekeys = "liping";
    
        private static SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512;
        private static Key key;
    
    //    @Value("${com.idoipo.jwt.encodedKey}")
    //    private String encodedKey;
    
        /**
         * 初始化操作 @PostConstruct初始化完成后执行
         */
    //    @PostConstruct
    //    public void init() {
    //        signatureAlgorithm = SignatureAlgorithm.HS512;
    //        key = deserializeKey(encodedKey);
    //    }
    
        /**
         * 生成加密解密key
         * @return
         */
        public static Key deserializeKey() {
            byte[] decodedKey = Base64.getDecoder().decode(encodekeys);
    
            Key key = new SecretKeySpec(decodedKey, JWTService.signatureAlgorithm.getJcaName());
            return key;
        }
    
        /**
         * 创建token 参数应该为自定义模型去传,用来设置token所携带字段
         * @return
         */
        public static String createToken(){
            key = deserializeKey();
            String token = Jwts.builder()
                    .setSubject(UUID.randomUUID().toString())
                    .claim("userName", "liping")
                    .setIssuer("lp")
                    .setAudience("xixi")
                    .signWith(signatureAlgorithm, key).compact();
            return token;
        }
    
        public static String parseToken(String token){
            key = deserializeKey();
            Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
            return  claims.get("userName").toString();
        }
    
        public static void main(String[] args) {
            String token  = JWTService.createToken();
            System.out.println(token);
            String userName = JWTService.parseToken(token);
            System.out.println(userName);
        }
        
    
    
    }
  • 相关阅读:
    记录一次linux centos7被hack的填坑记录-20201015
    linux端口转发:分为本机端口转发和将本机端口转发到其他机器 这2种情况
    proxmox通过spice来连接
    PAT L3-015. 球队“食物链”
    蓝桥杯模拟一 封印之门
    蓝桥杯模拟一 数列求值
    第13届景驰-埃森哲杯广东工业大学ACM程序设计大赛 K 密码
    计蒜客 蓝桥杯模拟五 合并数字
    PAT L3-017. 森森快递
    PAT L1-046. 整除光棍
  • 原文地址:https://www.cnblogs.com/keepMoveForevery/p/9703365.html
Copyright © 2011-2022 走看看