/// <summary>
    /// Computes the Client Assertion portion of the JWT
    /// </summary>
    /// <param name="header">The JSON Web Token header</param>
    /// <param name="claimSet">The JSON Web Token claim set</param>
    /// <param name="clientSecret">The client's secret</param>
    /// <returns>The assertion</returns>
    public string BuildAssertion(JWTHeader header, JWTClaimSet claimSet, string clientSecret)
    {
        // Serialize the header and claimSet
        string serializedHeader = JsonConvert.SerializeObject(header);
        string serializedClaimSet = JsonConvert.SerializeObject(claimSet);

        // Base64Encode the header and claimSet
        string encodedHeader = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(serializedHeader));
        string encodedClaimSet = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(serializedClaimSet));

        // Concatenate the header and the claims separated with a '.': [header].[claims]
        string message = string.Join(".", encodedHeader, encodedClaimSet);

        // Apply an HMAC/SHA-256 hash* to the concatenated content using the Client Secret as the key
        HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(clientSecret));
        byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));

        // Base64Encode the result of the hash
        string signature = Convert.ToBase64String(hash);

        // Combine the encoded elements as follows [header].[claims].[hash]
        string assertion = string.Join(".", encodedHeader, encodedClaimSet, signature);
        return assertion;
    }
    /// <summary>
    /// Retrieves a new token from Webtrends auth service
    /// </summary>
    public string Execute()
    {
        var builder = new JWTBuilder();
        var header = new JWTHeader
        {
            Type = "JWT",
            Algorithm = "HS256"
        };
        var claimSet = new JWTClaimSet
        {
            Issuer = clientId,
            Principal = clientId,
            Audience = audience,
            Expiration = DateTime.Now.AddSeconds(30),
            Scope = scope
        };

        string assertion = builder.BuildAssertion(header, claimSet, clientSecret);
        var client = new RestClient(authUrl);
        var request = new RestRequest("token/", Method.POST);
        request.AddParameter("client_id", clientId);
        request.AddParameter("client_assertion", assertion);
        request.AddParameter("grant_type", "client_credentials");
        request.AddParameter("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");

        var response = client.Execute(request).Content;
        return (string)JObject.Parse(response)["access_token"];
    }
    /// <summary>
    /// Retrieves a new token from Webtrends auth service
    /// </summary>
    public string Execute()
    {
        var builder = new JWTBuilder();
        var header = new JWTHeader
        {
            Type = "JWT",
            Algorithm = "HS256"
        };
        var claimSet = new JWTClaimSet
        {
            Issuer = clientId,
            Principal = clientId,
            Audience = audience,
            Expiration = DateTime.Now.ToUniversalTime().AddSeconds(30),
            Scope = scope
        };

        string assertion = builder.BuildAssertion(header, claimSet, clientSecret);
        var client = new RestClient(authUrl);
        var request = new RestRequest("token/", Method.POST);
        request.AddParameter("client_id", clientId);
        request.AddParameter("client_assertion", assertion);
        request.AddParameter("grant_type", "client_credentials");
        request.AddParameter("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");

        var response = client.Execute(request).Content;
        return (string)JObject.Parse(response)["access_token"];
    }
        private static JsonWebToken Create(string issuer, string audience, DateTime validFrom, DateTime validTo, DateTime issuedAt, IEnumerable <Claim> additionalClaims, JsonWebToken actor, string actorToken, VssSigningCredentials credentials, bool allowExpiredCertificate)
        {
            ArgumentUtility.CheckStringForNullOrEmpty(issuer, nameof(issuer));
            ArgumentUtility.CheckStringForNullOrEmpty(audience, nameof(audience)); // Audience isn't actually required...

            validFrom = validFrom == default(DateTime) ? DateTime.UtcNow : validFrom.ToUniversalTime();
            validTo   = validTo == default(DateTime) ? DateTime.UtcNow + TimeSpan.FromSeconds(DefaultLifetime) : validTo.ToUniversalTime();
            //issuedAt is optional, and breaks certain scenarios if it is present, and breaks others if it is not.
            //so only include it if it is explicitly set.
            issuedAt = issuedAt == default(DateTime) ? default(DateTime) : issuedAt.ToUniversalTime();

            JWTHeader  header  = GetHeader(credentials, allowExpiredCertificate);
            JWTPayload payload = new JWTPayload(additionalClaims)
            {
                Issuer = issuer, Audience = audience, ValidFrom = validFrom, ValidTo = validTo, IssuedAt = issuedAt
            };

            if (actor != null)
            {
                payload.Actor = actor;
            }
            else if (actorToken != null)
            {
                payload.ActorToken = actorToken;
            }

            byte[] signature = GetSignature(header, payload, header.Algorithm, credentials);

            return(new JsonWebToken(header, payload, signature));
        }
示例#5
0
 public IActionResult CheckToken(string _token)
 {
     if (_token == null)
     {
         return(BadRequest("初次登陆,请使用ID与密码登录"));
     }
     else
     {
         if (JWTHelper.IsOkToken(_token))
         {
             JWTHeader header = JWTHelper.GerHeaderFromToken(_token);
             string    Hd     = header.expTime.ToString();
             string    Now    = DateTime.Now.ToString();
             if (DateTime.Compare(Convert.ToDateTime(Now), Convert.ToDateTime(Hd)) <= 0)
             {
                 return(Ok());
             }
             else
             {
                 return(BadRequest("证书过期,请重新登录"));
             }
         }
         else
         {
             return(BadRequest("验证证书错误,请使用ID与密码登录"));
         }
     }
 }
 private JsonWebToken(JWTHeader header, JWTPayload payload, byte[] signature)
 {
     ArgumentUtility.CheckForNull(header, nameof(header));
     ArgumentUtility.CheckForNull(payload, nameof(payload));
     //signature allowed to be null
     _header    = header;
     _payload   = payload;
     _signature = signature;
 }
示例#7
0
        /// <summary>
        /// 生成JwtToken
        /// </summary>
        /// <param name="jwtPayload">非隐私的用户数据</param>
        /// <returns></returns>

        public static string SetJwtEncode(JWTPayload jwtPayload)
        {
            try
            {
                JWTHeader jwtHeader = new JWTHeader();
                //格式如下
                //var payload = new Dictionary<string, object>
                //{
                //    { "username","admin" },
                //    { "pwd", "claim2-value" }
                //};
                //--------------加密器配置
                IJwtAlgorithm     algorithm  = new HMACSHA256Algorithm();
                IJsonSerializer   serializer = new JsonNetSerializer();
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtEncoder       encoder    = new JwtEncoder(algorithm, serializer, urlEncoder);
                //--------------------
                //json转string
                string strHeader  = JsonConvert.SerializeObject(jwtHeader);
                string strPayload = JsonConvert.SerializeObject(jwtPayload);

                //64位加密
                byte[] encHeaderBuff  = System.Text.Encoding.UTF8.GetBytes(strHeader);
                string basHeader      = Convert.ToBase64String(encHeaderBuff);
                byte[] encPayloadBuff = System.Text.Encoding.UTF8.GetBytes(strPayload);
                string basPayload     = Convert.ToBase64String(encPayloadBuff);


                string value = basHeader + "." + basPayload;
                //debug
                //byte[] SHA256Data = System.Text.Encoding.UTF8.GetBytes(value);
                //SHA256Managed sha256 = new SHA256Managed();
                //byte[] SHA256Reslut = sha256.ComputeHash(SHA256Data);

                //var Payload = new Dictionary<string, object>
                //{
                //    { "UserID",jwtPayload.UserID},
                //    { "UserType",jwtPayload.}
                //}
                //string basSignature = encoder.Encode(value, saltKey);

                string basSignature = encoder.Encode(value, saltKey);
                string token        = string.Format("{0}.{1}.{2}", basHeader, basPayload, basSignature);

                return(token);
                //--------
            }
            //如果创建token失败则返回空值
            catch (Exception) { return(string.Empty); }
        }
示例#8
0
 /// <summary>
 /// 获取Token信息,解密获得其他信息
 /// </summary>
 /// <param name="value"></param>
 /// <returns>头部信息</returns>
 public static JWTHeader GetHeader(string value)
 {
     try
     {
         //先把加密的文字解密
         byte[] basHeader = Convert.FromBase64String(value);
         string decHeader = System.Text.Encoding.UTF8.GetString(basHeader);
         //将解密后的数据序列化成对象
         JWTHeader header = JsonConvert.DeserializeObject <JWTHeader>(decHeader);
         return(header);
     }
     catch (Exception)
     {
         return(null);
     }
 }
示例#9
0
        private static string getAssertion(string serverId, string privateKey)
        {
            ArrayList segments = new ArrayList();

            JWTHeader jwtHeader = new JWTHeader();

            jwtHeader.alg = "RS256";
            jwtHeader.typ = "JWT";
            string header = jwtHeader.ToJSON();

            JWTClaim jwtClaim = new JWTClaim();

            jwtClaim.iss = serverId;
            jwtClaim.iat = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
            jwtClaim.exp = jwtClaim.iat + 1800;
            string claim = jwtClaim.ToJSON();

            byte[] headerBytes  = Encoding.UTF8.GetBytes(header);
            byte[] payloadBytes = Encoding.UTF8.GetBytes(claim);

            segments.Add(base64UrlEncode(headerBytes));
            segments.Add(base64UrlEncode(payloadBytes));

            string stringToSign = string.Join(".", segments.ToArray());


            byte[] bytesToSign = Encoding.UTF8.GetBytes(stringToSign);
            byte[] keyBytes    = Convert.FromBase64String(privateKey);


            ////////////////////RSA SHA-256 암호화////////////////////
            var asymmetricKeyParameter = PrivateKeyFactory.CreateKey(keyBytes);
            var rsaKeyParameter        = (RsaKeyParameters)asymmetricKeyParameter;

            ISigner sig = SignerUtilities.GetSigner("SHA256withRSA");

            sig.Init(true, rsaKeyParameter);

            sig.BlockUpdate(bytesToSign, 0, bytesToSign.Length);
            byte[] signature = sig.GenerateSignature();
            //////////////////////////////////////////////////////////

            segments.Add(base64UrlEncode(signature));
            return(string.Join(".", segments.ToArray()));
        }
        //OnDeserialized never gets called by serializer because we have a custom converter, so call this
        //from there...
        //[OnDeserialized]
        private void OnDeserialized(/*StreamingContext context*/)
        {
            if (string.IsNullOrEmpty(this._encodedToken))
            {
                throw new JsonWebTokenDeserializationException();
            }

            string[] fields = this._encodedToken.Split('.');

            if (fields.Length != 3)
            {
                throw new JsonWebTokenDeserializationException();
            }

            this._header  = JsonWebTokenUtilities.JsonDecode <JWTHeader>(fields[0]);
            this._payload = JsonWebTokenUtilities.JsonDecode <JWTPayload>(fields[1]);
            if (!string.IsNullOrEmpty(fields[2]))
            {
                this._signature = fields[2].FromBase64StringNoPadding();
            }
        }
        private static JWTHeader GetHeader(VssSigningCredentials credentials, bool allowExpired)
        {
            //note credentials are allowed to be null here, see ValidateSigningCredentials
            JWTHeader header = new JWTHeader();

            JWTAlgorithm alg = JsonWebTokenUtilities.ValidateSigningCredentials(credentials, allowExpired);

            header.Algorithm = alg;

            if (alg != JWTAlgorithm.None)
            {
                // Some signing credentials may need to set headers for the JWT
                var jwtHeaderProvider = credentials as IJsonWebTokenHeaderProvider;
                if (jwtHeaderProvider != null)
                {
                    jwtHeaderProvider.SetHeaders(header);
                }
            }

            return(header);
        }
        public string GenerateJWT()
        {
            JWTHeader Header  = new JWTHeader();
            JWTBody   Payload = new JWTBody
            {
                Username = this.Username,
                Group    = this.Group,
                Iat      = DateTime.Now
            };

            string EncodedHeader  = Convert.ToBase64String(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(Header)));
            string EncodedPayload = Convert.ToBase64String(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(Payload)));
            string Message        = EncodedHeader + "." + EncodedPayload;

            //TODO: Put the file path in a config file somewhere
            try
            {
                return(Message + "." + RS256.Sign(Encoding.ASCII.GetBytes(Message)));
            }catch
            {
                return("fail!");
            }
        }
        //if we alread have the alg, we assume that the creds have been validated already,
        //to save the expense of validating twice in the create function...
        private static byte[] GetSignature(JWTHeader header, JWTPayload payload, JWTAlgorithm alg, VssSigningCredentials signingCredentials)
        {
            if (alg == JWTAlgorithm.None)
            {
                return(null);
            }

            ArgumentUtility.CheckForNull(header, nameof(header));
            ArgumentUtility.CheckForNull(payload, nameof(payload));

            string encoding = string.Format("{0}.{1}", header.JsonEncode(), payload.JsonEncode());

            byte[] bytes = Encoding.UTF8.GetBytes(encoding);

            switch (alg)
            {
            case JWTAlgorithm.HS256:
            case JWTAlgorithm.RS256:
                return(signingCredentials.SignData(bytes));

            default:
                throw new InvalidOperationException();
            }
        }
    /// <summary>
    /// Computes the Client Assertion portion of the JWT
    /// </summary>
    /// <param name="header">The JSON Web Token header</param>
    /// <param name="claimSet">The JSON Web Token claim set</param>
    /// <param name="clientSecret">The client's secret</param>
    /// <returns>The assertion</returns>
    public string BuildAssertion(JWTHeader header, JWTClaimSet claimSet, string clientSecret)
    {
        // Serialize the header and claimSet
        string serializedHeader = JsonConvert.SerializeObject(header);
        string serializedClaimSet = JsonConvert.SerializeObject(claimSet);

        // Base64Encode the header and claimSet
        string encodedHeader = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(serializedHeader));
        string encodedClaimSet = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(serializedClaimSet));

        // Concatenate the header and the claims separated with a '.': [header].[claims]
        string message = string.Join(".", encodedHeader, encodedClaimSet);

        // Apply an HMAC/SHA-256 hash* to the concatenated content using the Client Secret as the key
        HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(clientSecret));
        byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));

        // Base64Encode the result of the hash
        string signature = Convert.ToBase64String(hash);

        // Combine the encoded elements as follows [header].[claims].[hash]
        string assertion = string.Join(".", encodedHeader, encodedClaimSet, signature);
        return assertion;
    }
示例#15
0
        public static string SignData(JWTPayload payload, byte[] privateKey, string certificatePassword)
        {
            X509Certificate2 x509Certificate2 = new X509Certificate2(privateKey, certificatePassword);


            JWTHeader header      = new JWTHeader();
            string    jsonHeader  = JsonConvert.SerializeObject(header);
            string    jsonPayload = JsonConvert.SerializeObject(payload);

            byte[]        bytesHeader = Encoding.UTF8.GetBytes(jsonHeader);
            byte[]        bytesPaylod = Encoding.UTF8.GetBytes(jsonPayload);
            List <string> segments    = new List <string>();

            segments.Add(Base64UrlEncode(bytesHeader));
            segments.Add(Base64UrlEncode(bytesPaylod));
            byte[] bytesToSign = Encoding.UTF8.GetBytes(string.Join(".", segments.ToArray()));

            using (RSA rsa = x509Certificate2.GetRSAPrivateKey())
            {
                byte[] signedData = rsa.SignData(bytesToSign, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
                segments.Add(Base64UrlEncode(signedData));
                return(string.Join(".", segments.ToArray()));
            }
        }
示例#16
0
 public IJWTBuilder WithHeader(JWTHeader header)
 {
     JWTHeader = header;
     return(this);
 }
        private static byte[] GetSignature(JWTHeader header, JWTPayload payload, VssSigningCredentials credentials, bool allowExpired)
        {
            JWTAlgorithm alg = JsonWebTokenUtilities.ValidateSigningCredentials(credentials, allowExpired);

            return(GetSignature(header, payload, alg, credentials));
        }