• 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);
        }
        
    
    
    }
  • 相关阅读:
    错误设置子网掩码的结果
    子网掩码
    网络笔记
    网络笔记
    命名空间
    命名空间
    多重继承和虚继承
    多重继承和虚继承
    windows抓包程序
    windows抓包程序
  • 原文地址:https://www.cnblogs.com/keepMoveForevery/p/9703365.html
Copyright © 2020-2023  润新知