/// <inheritdoc /> /// <exception cref="ArgumentNullException" /> public string Encode(IDictionary <string, object> extraHeaders, object payload, byte[] key) { if (payload is null) { throw new ArgumentNullException(nameof(payload)); } if (!_algorithm.IsAsymmetric() && key is null) { throw new ArgumentNullException(nameof(key)); } var header = extraHeaders is null ? new Dictionary <string, object>(2, StringComparer.OrdinalIgnoreCase) : new Dictionary <string, object>(extraHeaders, StringComparer.OrdinalIgnoreCase); if (!header.ContainsKey("typ")) { header.Add("typ", "JWT"); } header.Add("alg", _algorithm.Name); var headerBytes = GetBytes(_jsonSerializer.Serialize(header)); var payloadBytes = GetBytes(_jsonSerializer.Serialize(payload)); var headerSegment = _urlEncoder.Encode(headerBytes); var payloadSegment = _urlEncoder.Encode(payloadBytes); var stringToSign = headerSegment + "." + payloadSegment; var bytesToSign = GetBytes(stringToSign); var signature = _algorithm.Sign(key, bytesToSign); var signatureSegment = _urlEncoder.Encode(signature); return(stringToSign + "." + signatureSegment); }
/// <inheritdoc /> /// <exception cref="ArgumentNullException" /> public string Encode(IDictionary <string, object> extraHeaders, object payload, byte[] key) { if (payload is null) { throw new ArgumentNullException(nameof(payload)); } if (!_algorithm.IsAsymmetric() && key is null) { throw new ArgumentNullException(nameof(key)); } var segments = new List <string>(3); var header = extraHeaders is null ? new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase) : new Dictionary <string, object>(extraHeaders, StringComparer.OrdinalIgnoreCase); header.Add("typ", "JWT"); header.Add("alg", _algorithm.Name); var headerBytes = GetBytes(_jsonSerializer.Serialize(header)); var payloadBytes = GetBytes(_jsonSerializer.Serialize(payload)); segments.Add(_urlEncoder.Encode(headerBytes)); segments.Add(_urlEncoder.Encode(payloadBytes)); var stringToSign = String.Join(".", segments.ToArray()); var bytesToSign = GetBytes(stringToSign); var signature = _algorithm.Sign(key, bytesToSign); segments.Add(_urlEncoder.Encode(signature)); return(String.Join(".", segments.ToArray())); }