JWT的一种实现

网上看到的JWT的一种实现。

        // c# Hmacsha256
        protected String HMacSha256Hash(String key, String message)
        {
            var keyBytes = Encoding.UTF8.GetBytes(key);
            using (var hmacsha256 = new HMACSHA256(keyBytes))
            {
                var buffer = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(message));
                var b64 = Base64UrlSafeString(buffer);
                return b64;
            }
        }
        
        protected String Base64UrlSafeString(Byte[] bytes)
        {
            var b64 = Convert.ToBase64String(bytes);
            return b64.Replace("=", "").Replace("+", "-").Replace("/", "_");
        }
        
        // c# jwt 
        public void testJWT()
        {
            String secret = "eerp";
            String header = "{\"type\":\"JWT\",\"alg\":\"HS256\"}";
            String claim = "{\"iss\":\"cnooc\", \"sub\":\"yrm\", \"username\":\"yrm\", \"admin\":true}";
        
            var encoding = Encoding.UTF8;
            var base64Header = Base64UrlSafeString(encoding.GetBytes(header));
            var base64Claim = Base64UrlSafeString(encoding.GetBytes(claim));
            var signature = HMacSha256Hash(secret, base64Header + "." + base64Claim);
        
            var jwt = base64Header + "." + base64Claim + "." + signature;
            Console.WriteLine(jwt);
        
        }

 

posted @ 2024-08-26 20:30  法宝  阅读(3)  评论(0编辑  收藏  举报