Skip to content

Commit

Permalink
Adding non-throwing methods TryValidate to JwtValidator (#186)
Browse files Browse the repository at this point in the history
- Adding TryValidate to JwtValidator
- Updating tests
- Adding InternalsVisibleTo
  • Loading branch information
abatishchev authored Feb 10, 2019
1 parent 9ce7c0d commit 59c1623
Show file tree
Hide file tree
Showing 17 changed files with 294 additions and 137 deletions.
2 changes: 1 addition & 1 deletion src/JWT/Builder/HeaderName.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public enum HeaderName

[Description("alg")]
Algorithm,

[Description("kid")]
KeyId
}
Expand Down
54 changes: 24 additions & 30 deletions src/JWT/Builder/JwtBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public JwtBuilder WithDateTimeProvider(IDateTimeProvider provider)
/// <summary>
/// Sets JWT encoder.
/// </summary>
/// <returns>Current builder instance</returns>
/// <returns>Current builder instance</returns>
public JwtBuilder WithEncoder(IJwtEncoder encoder)
{
_encoder = encoder;
Expand All @@ -102,7 +102,7 @@ public JwtBuilder WithEncoder(IJwtEncoder encoder)
/// <summary>
/// Sets JWT decoder.
/// </summary>
/// <returns>Current builder instance</returns>
/// <returns>Current builder instance</returns>
public JwtBuilder WithDecoder(IJwtDecoder decoder)
{
_decoder = decoder;
Expand All @@ -115,7 +115,7 @@ public JwtBuilder WithDecoder(IJwtDecoder decoder)
/// <remarks>
/// Required to decode with verification.
/// </remarks>
/// <returns>Current builder instance</returns>
/// <returns>Current builder instance</returns>
public JwtBuilder WithValidator(IJwtValidator validator)
{
_validator = validator;
Expand Down Expand Up @@ -190,7 +190,7 @@ public JwtBuilder WithVerifySignature(bool verify)
/// <exception cref="InvalidOperationException">Thrown if either algorithm, serializer, encoder or secret is null</exception>
public string Build()
{
if (_encoder == null)
if (_encoder is null)
TryCreateEncoder();

EnsureCanBuild();
Expand All @@ -205,7 +205,7 @@ public string Build()
/// <returns>The JSON payload</returns>
public string Decode(string token)
{
if (_decoder == null)
if (_decoder is null)
TryCreateDecoder();

return _verify ? _decoder.Decode(token, _secrets, _verify) : _decoder.Decode(token);
Expand All @@ -218,19 +218,19 @@ public string Decode(string token)
/// <returns>The payload converted to <see cref="T" /></returns>
public T Decode<T>(string token)
{
if (_decoder == null)
if (_decoder is null)
TryCreateDecoder();

return _verify ? _decoder.DecodeToObject<T>(token, _secrets[0], _verify) : _decoder.DecodeToObject<T>(token);
}

private void TryCreateEncoder()
{
if (_algorithm == null)
if (_algorithm is null)
throw new InvalidOperationException($"Can't instantiate {nameof(JwtEncoder)}. Call {nameof(WithAlgorithm)}.");
if (_serializer == null)
if (_serializer is null)
throw new InvalidOperationException($"Can't instantiate {nameof(JwtEncoder)}. Call {nameof(WithSerializer)}");
if (_urlEncoder == null)
if (_urlEncoder is null)
throw new InvalidOperationException($"Can't instantiate {nameof(JwtEncoder)}. Call {nameof(WithUrlEncoder)}.");

_encoder = new JwtEncoder(_algorithm, _serializer, _urlEncoder);
Expand All @@ -240,11 +240,11 @@ private void TryCreateDecoder()
{
TryCreateValidator();

if (_serializer == null)
if (_serializer is null)
throw new InvalidOperationException($"Can't instantiate {nameof(JwtDecoder)}. Call {nameof(WithSerializer)}.");
if (_validator == null)
if (_validator is null)
throw new InvalidOperationException($"Can't instantiate {nameof(JwtDecoder)}. Call {nameof(WithValidator)}.");
if (_urlEncoder == null)
if (_urlEncoder is null)
throw new InvalidOperationException($"Can't instantiate {nameof(JwtDecoder)}. Call {nameof(WithUrlEncoder)}.");

EnsureCanDecode();
Expand All @@ -257,9 +257,9 @@ private void TryCreateValidator()
if (_validator != null)
return;

if (_serializer == null)
if (_serializer is null)
throw new InvalidOperationException($"Can't instantiate {nameof(JwtValidator)}. Call {nameof(WithSerializer)}.");
if (_dateTimeProvider == null)
if (_dateTimeProvider is null)
throw new InvalidOperationException($"Can't instantiate {nameof(JwtValidator)}. Call {nameof(WithDateTimeProvider)}.");

_validator = new JwtValidator(_serializer, _dateTimeProvider);
Expand Down Expand Up @@ -289,14 +289,12 @@ private void EnsureCanDecode()
/// <summary>
/// Checks whether enough dependencies were supplied to build a new token.
/// </summary>
private bool CanBuild()
{
return _algorithm != null &&
_serializer != null &&
_urlEncoder != null &&
_jwt.Payload != null &&
_algorithm.IsAsymmetric || HasOnlyOneSecret();
}
private bool CanBuild() =>
_algorithm != null &&
_serializer != null &&
_urlEncoder != null &&
_jwt.Payload != null &&
(_algorithm.IsAsymmetric || HasOnlyOneSecret());

/// <summary>
/// Checks whether enough dependencies were supplied to decode a token.
Expand All @@ -316,18 +314,14 @@ private bool CanDecode()
/// <summary>
/// Checks if any secret was supplied to use in token decoding
/// </summary>
private bool HasSecrets()
{
return _secrets != null && _secrets.Length > 0;
}
private bool HasSecrets() =>
_secrets != null && _secrets.Length > 0;

/// <summary>
/// Checks if there is only one secret was supplied for token encoding
/// </summary>
/// <returns></returns>
private bool HasOnlyOneSecret()
{
return _secrets != null && _secrets.Length == 1;
}
private bool HasOnlyOneSecret() =>
_secrets != null && _secrets.Length == 1;
}
}
8 changes: 4 additions & 4 deletions src/JWT/IJwtDecoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public interface IJwtDecoder
/// <param name="verify">Whether to verify the signature (default is true)</param>
/// <returns>A string containing the JSON payload</returns>
string Decode(string token, string key, bool verify);

/// <summary>
/// Given a JWT, decodes it and return the JSON payload.
/// </summary>
Expand Down Expand Up @@ -72,7 +72,7 @@ public interface IJwtDecoder
/// <exception cref="SignatureVerificationException">Thrown if the verify parameter was true and the signature was NOT valid or if the JWT was signed with an unsupported algorithm</exception>
/// <exception cref="TokenExpiredException">Thrown if the verify parameter was true and the token has an expired exp claim</exception>
IDictionary<string, object> DecodeToObject(string token, string key, bool verify);

/// <summary>
/// Given a JWT, decodes it and return the payload as an object.
/// </summary>
Expand All @@ -94,7 +94,7 @@ public interface IJwtDecoder
/// <exception cref="SignatureVerificationException">Thrown if the verify parameter was true and the signature was NOT valid or if the JWT was signed with an unsupported algorithm</exception>
/// <exception cref="TokenExpiredException">Thrown if the verify parameter was true and the token has an expired exp claim</exception>
IDictionary<string, object> DecodeToObject(string token, byte[] key, bool verify);

/// <summary>
/// Given a JWT, decodes it and return the payload as an object.
/// </summary>
Expand Down Expand Up @@ -129,7 +129,7 @@ public interface IJwtDecoder
/// <exception cref="SignatureVerificationException">Thrown if the verify parameter was true and the signature was NOT valid or if the JWT was signed with an unsupported algorithm</exception>
/// <exception cref="TokenExpiredException">Thrown if the verify parameter was true and the token has an expired exp claim</exception>
T DecodeToObject<T>(string token, string key, bool verify);

/// <summary>
/// Given a JWT, decodes it and return the payload as an object.
/// </summary>
Expand Down
2 changes: 1 addition & 1 deletion src/JWT/JWT.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
<PackageProjectUrl>https://github.com/jwt-dotnet/jwt</PackageProjectUrl>
<Authors>John Sheehan, Michael Lehenbauer, Alexander Batishchev</Authors>
<PackageLicenseUrl>https://creativecommons.org/publicdomain/zero/1.0/</PackageLicenseUrl>
<Version>5.0.0-beta4</Version>
<Version>5.0.0-beta5</Version>
<PackageTags>jwt json</PackageTags>
<FileVersion>5.0.0.0</FileVersion>
<AssemblyVersion>5.0.0.0</AssemblyVersion>
Expand Down
2 changes: 1 addition & 1 deletion src/JWT/JwtBase64UrlEncoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public sealed class JwtBase64UrlEncoder : IBase64UrlEncoder
/// <exception cref="ArgumentOutOfRangeException" />
public string Encode(byte[] input)
{
if (input == null)
if (input is null)
throw new ArgumentNullException(nameof(input));
if (input.Length == 0)
throw new ArgumentOutOfRangeException(nameof(input));
Expand Down
28 changes: 12 additions & 16 deletions src/JWT/JwtDecoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public string Decode(string token, byte[] key, bool verify)
{
if (String.IsNullOrWhiteSpace(token))
throw new ArgumentException(nameof(token));
if (key == null)
if (key is null)
throw new ArgumentNullException(nameof(key));
if (key.Length == 0)
throw new ArgumentOutOfRangeException(nameof(key));
Expand All @@ -99,9 +99,9 @@ public string Decode(string token, IReadOnlyCollection<byte[]> keys, bool verify
{
if (String.IsNullOrWhiteSpace(token))
throw new ArgumentException(nameof(token));
if (keys == null || keys.Count == 0)
if (keys is null)
throw new ArgumentNullException(nameof(keys));
if (!DoesKeysHaveValues(keys))
if (keys.Count == 0 || !AllKeysHaveValues(keys))
throw new ArgumentOutOfRangeException(nameof(keys));

if (verify)
Expand Down Expand Up @@ -209,9 +209,9 @@ public T DecodeToObject<T>(string token, IReadOnlyCollection<byte[]> keys, bool
/// <exception cref="FormatException" />
public void Validate(JwtParts jwt, byte[] key)
{
if (jwt == null)
if (jwt is null)
throw new ArgumentNullException(nameof(jwt));
if (key == null)
if (key is null)
throw new ArgumentNullException(nameof(key));
if (key.Length == 0)
throw new ArgumentOutOfRangeException(nameof(key));
Expand Down Expand Up @@ -246,11 +246,11 @@ public void Validate(JwtParts jwt, byte[] key)
/// <exception cref="FormatException" />
public void Validate(JwtParts jwt, IReadOnlyCollection<byte[]> keys)
{
if (jwt == null)
if (jwt is null)
throw new ArgumentNullException(nameof(jwt));
if (keys == null || keys.Count == 0)
if (keys is null)
throw new ArgumentNullException(nameof(keys));
if (!DoesKeysHaveValues(keys))
if (keys.Count == 0 || !AllKeysHaveValues(keys))
throw new ArgumentOutOfRangeException(nameof(keys));

var crypto = _urlEncoder.Decode(jwt.Signature);
Expand All @@ -277,14 +277,10 @@ public void Validate(JwtParts jwt, IReadOnlyCollection<byte[]> keys)

private static string GetString(byte[] bytes) => Encoding.UTF8.GetString(bytes);

private static IReadOnlyCollection<byte[]> GetBytes(IEnumerable<string> input)
{
return input.Select(key => GetBytes(key)).ToArray();
}
private static IReadOnlyCollection<byte[]> GetBytes(IEnumerable<string> input) =>
input.Select(key => GetBytes(key)).ToArray();

private static bool DoesKeysHaveValues(IReadOnlyCollection<byte[]> keys)
{
return keys.Any(key => key.Length != 0);
}
private static bool AllKeysHaveValues(IReadOnlyCollection<byte[]> keys) =>
keys.All(key => key.Length != 0);
}
}
2 changes: 1 addition & 1 deletion src/JWT/JwtEncoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public JwtEncoder(IJwtAlgorithm algorithm, IJsonSerializer jsonSerializer, IBase
/// <exception cref="ArgumentNullException" />
public string Encode(IDictionary<string, object> extraHeaders, object payload, byte[] key)
{
if (payload == null)
if (payload is null)
throw new ArgumentNullException(nameof(payload));

var segments = new List<string>(3);
Expand Down
2 changes: 1 addition & 1 deletion src/JWT/JwtParts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public JwtParts(string token)
/// <exception cref="ArgumentOutOfRangeException" />
public JwtParts(string[] parts)
{
if (parts == null)
if (parts is null)
throw new ArgumentNullException(nameof(parts));
if (parts.Length != 3)
throw new InvalidTokenPartsException(nameof(parts));
Expand Down
Loading

0 comments on commit 59c1623

Please sign in to comment.