/// <summary> /// Decodes asynchronously the string representation of this object /// </summary> /// <param name="verify">Verifies if the token is valid</param> /// <returns></returns> public Task DecodeAsync(bool verify) { var task = Task.Run(() => { DateTime startTime = DateTime.Now; // Checking if token is empty, and raising an exception if true if (string.IsNullOrEmpty(Token)) { throw new ArgumentNullException("Token"); } // breaking the token into the constituting parts and checking if there is any signature present // on a valid token we need to always have a three part token, even if the signature is // not present there should always be 2 dots. string[] parts = Token.Split('.'); if (parts.Count() < 3) { throw new ArgumentException("Token not correcty constructed."); } // Decoding the header and the payload for verification and parse string decodedHeader = parts[0].Base64UrlDecode().GetString(); string decodedPayload = parts[1].Base64UrlDecode().GetString(); string signature = parts[2]; // setting the raw header and raw payload properties values RawHeader = decodedHeader; RawPayload = decodedPayload; // trying to parse the header into a JoseHeader as expected JoseHeader.TryParse(decodedHeader, out JoseHeader header); Header = header; // Trying to parse the payload into a JWT Claim, if this is not the case we will store the raw data and // a string as a payload to later be analized JsonWebTokenClaim.TryParse(decodedPayload, out JsonWebTokenClaim claim); if (claim != null) { Payload = claim; } else { Payload = decodedPayload; } //Checking if we can verify the token if ((Header?.Algorithm != JWTAlgorithm.Empty || Header?.Algorithm != JWTAlgorithm.none) && !string.IsNullOrEmpty(signature)) { if (verify) { Verify(); } } TimeSpan ts = DateTime.Now.Subtract(startTime); Console.WriteLine($"=> Decode took: {ts.Milliseconds}"); }); return(task); }
public static bool TryParse(IDictionary <string, object> inputDic, out JsonWebTokenClaim claim) { claim = null; try { claim = new JsonWebTokenClaim(); foreach (var item in inputDic) { claim.Add(item.Key, item.Value); } return(true); } catch { } return(false); }
public static bool TryParse(string input, out JsonWebTokenClaim claim) { claim = null; Dictionary <string, object> items = null; IJsonSerializer jsonSerializer = new DefaultJsonSerializer(); try { items = jsonSerializer.Deserialize <Dictionary <string, object> >(input); if (items != null) { claim = new JsonWebTokenClaim(); foreach (var item in items) { claim.Add(item.Key, item.Value); } } return(true); } catch { } return(false); }