Skip to content

Commit

Permalink
Merge pull request #5 from SiroccoHub/develop
Browse files Browse the repository at this point in the history
update for 1.0.1
  • Loading branch information
arichika committed Dec 21, 2015
2 parents 15c6d22 + 2299ad9 commit bf57ba3
Show file tree
Hide file tree
Showing 6 changed files with 105 additions and 38 deletions.
23 changes: 19 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,19 @@
This library supports generating and decoding [JSON Web Tokens](http://tools.ietf.org/html/draft-jones-json-web-token-10).
forked from [jwt-dotnet/jwt](https://github.com/jwt-dotnet/jwt)

## Features
* Support ASP.NET 5 MVC 6 (DNX).
* Two Extention Methods for Converting Unix Timestamp between .NET DateTime.
* Simple usage.

## Installation
Please download and compile it yourself. NuGet is [here](https://www.nuget.org/packages/JwtDnx/).
At first, You need to install Newtonsoft.Json. [FYI](http://www.newtonsoft.com/json).
and, Please download and compile JwtDnx yourself or Install by NuGet,

```console
PM> Install-Package JwtDnx
```
NuGet repo is [here](https://www.nuget.org/packages/JwtDnx/).

## Usage
### Creating Tokens
Expand Down Expand Up @@ -59,16 +70,20 @@ which will output:
As described in the [JWT RFC](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.4) the `exp` "claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing." If an `exp` claim is present and is prior to the current time the token will fail verification. The exp (expiry) value must be specified as the number of seconds since 1/1/1970 UTC.

```csharp
var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var now = Math.Round((DateTime.UtcNow - unixEpoch).TotalSeconds);
var now = DateTime.UtcNow.ToUnixTimeSeconds();
var payload = new Dictionary<string, object>()
{
{ "exp", now }
};
var secretKey = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";
string token = JwtDnx.JsonWebToken.Encode(payload, secretKey, JwtDnx.JwtHashAlgorithm.HS256);
string jsonPayload = JwtDnx.JsonWebToken.Decode(token, secretKey);
```

if you will decode json that has invalid Unix Timestamp, you'll get some exception.

string jsonPayload = JWT.JsonWebToken.Decode(token, secretKey); // JwtDnx.SignatureVerificationException!
```csharp
string jsonPayload = JwtDnx.JsonWebToken.Decode(token, secretKey); // JwtDnx.SignatureVerificationException!
```

### Configure JSON Serialization
Expand Down
42 changes: 21 additions & 21 deletions src/JwtDnx/JwtDnx.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public static string Encode(IDictionary<string, object> extraHeaders, object pay
/// <summary>
/// Creates a JWT given a payload, the signing key, and the algorithm to use.
/// </summary>
/// <param name="payload">An arbitrary payload (must be serializable to JSON via <see cref="System.Web.Script.Serialization.JavaScriptSerializer"/>).</param>
/// <param name="payload">An arbitrary payload.</param>
/// <param name="key">The key used to sign the token.</param>
/// <param name="algorithm">The hash algorithm to use.</param>
/// <returns>The generated JWT.</returns>
Expand All @@ -85,7 +85,7 @@ public static string Encode(object payload, byte[] key, JwtHashAlgorithm algorit
/// Creates a JWT given a set of arbitrary extra headers, a payload, the signing key, and the algorithm to use.
/// </summary>
/// <param name="extraHeaders">An arbitrary set of extra headers. Will be augmented with the standard "typ" and "alg" headers.</param>
/// <param name="payload">An arbitrary payload (must be serializable to JSON via <see cref="System.Web.Script.Serialization.JavaScriptSerializer"/>).</param>
/// <param name="payload">An arbitrary payload.</param>
/// <param name="key">The key bytes used to sign the token.</param>
/// <param name="algorithm">The hash algorithm to use.</param>
/// <returns>The generated JWT.</returns>
Expand All @@ -97,7 +97,7 @@ public static string Encode(IDictionary<string, object> extraHeaders, object pay
/// <summary>
/// Creates a JWT given a payload, the signing key, and the algorithm to use.
/// </summary>
/// <param name="payload">An arbitrary payload (must be serializable to JSON via <see cref="System.Web.Script.Serialization.JavaScriptSerializer"/>).</param>
/// <param name="payload">An arbitrary payload.</param>
/// <param name="key">The key used to sign the token.</param>
/// <param name="algorithm">The hash algorithm to use.</param>
/// <returns>The generated JWT.</returns>
Expand Down Expand Up @@ -152,29 +152,29 @@ private static void Verify(string decodedCrypto, string decodedSignature, string
{
if (decodedCrypto != decodedSignature)
{
throw new SignatureVerificationException(string.Format("Invalid signature. Expected {0} got {1}", decodedCrypto, decodedSignature));
throw new SignatureVerificationException(
$"Invalid signature. Expected {decodedCrypto} got {decodedSignature}");
}

// verify exp claim https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.4
var payloadData = JsonSerializer.Deserialize<Dictionary<string, object>>(payloadJson);
if (payloadData.ContainsKey("exp") && payloadData["exp"] != null)
if (!payloadData.ContainsKey("exp") || payloadData["exp"] == null) return;

// safely unpack a boxed int
int exp;
try
{
exp = Convert.ToInt32(payloadData["exp"]);
}
catch (Exception)
{
throw new SignatureVerificationException("Claim 'exp' must be an integer.");
}

var secondsSinceEpoch = Math.Round((DateTime.UtcNow - UnixEpoch).TotalSeconds);
if (secondsSinceEpoch >= exp)
{
// safely unpack a boxed int
int exp;
try
{
exp = Convert.ToInt32(payloadData["exp"]);
}
catch (Exception)
{
throw new SignatureVerificationException("Claim 'exp' must be an integer.");
}

var secondsSinceEpoch = Math.Round((DateTime.UtcNow - UnixEpoch).TotalSeconds);
if (secondsSinceEpoch >= exp)
{
throw new SignatureVerificationException("Token has expired.");
}
throw new SignatureVerificationException("Token has expired.");
}
}

Expand Down
30 changes: 30 additions & 0 deletions src/JwtDnx/JwtDnxExtentions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System;
namespace JwtDnx
{
public static class JwtDnxExtentions
{
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

/// <summary>
/// Convert from .NET DateTime to UnixTimeStamp.
/// (FYI in NET4.6 -> https://msdn.microsoft.com/en-us/library/system.datetimeoffset.tounixtimeseconds.aspx)
/// </summary>
/// <param name="dateTimeUtc">DateTimeUtc</param>
/// <returns>UnixTimeStamp</returns>
public static long ToUnixTimeSeconds(this DateTime dateTimeUtc)
{
return (long)Math.Round((dateTimeUtc.ToUniversalTime() - UnixEpoch).TotalSeconds);
}

/// <summary>
/// Convert from UnixTimeStamp to .NET DateTime.
/// (FYI in NET4.6 -> https://msdn.microsoft.com/en-us/library/system.datetimeoffset.tounixtimeseconds.aspx)
/// </summary>
/// <param name="unixTimeStamp">UnixTimeStamp</param>
/// <returns>DateTime by Utc</returns>
public static DateTime ToDateTiemUtc(this long unixTimeStamp)
{
return UnixEpoch.AddSeconds(unixTimeStamp);
}
}
}
10 changes: 3 additions & 7 deletions src/JwtDnx/project.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"version": "1.0.0-*",
"description": "JwtDnx Class Library",
"authors": [ "@arichika(arichika.taniguchi)" ],
"version": "1.0.1-*",
"description": "JwtDnx is JWT / JWS Implementation for .NET DNX (like ASP.NET 5 MVC 6)",
"authors": [ "@arichika (arichika.taniguchi)" ],
"tags": [ "" ],
"projectUrl": "https://github.com/SiroccoHub/JwtDnx",
"licenseUrl": "https://github.com/SiroccoHub/JwtDnx/blob/master/LICENSE.txt",
Expand All @@ -14,10 +14,6 @@
"dotnet5.4": {
"dependencies": {
"Microsoft.CSharp": "4.0.1-beta-23516",
"System.Collections": "4.0.11-beta-23516",
"System.Linq": "4.0.1-beta-23516",
"System.Runtime": "4.0.21-beta-23516",
"System.Threading": "4.0.11-beta-23516",
"System.Security.Cryptography.Algorithms": "4.0.0-beta-23516"
}
}
Expand Down
31 changes: 31 additions & 0 deletions test/JwtDnxTests/JwtDnxExtentionsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using JwtDnx;
using Xunit;

namespace JwtDnxTests
{
public class ExtentionsTests
{

private static DateTime _netDateTimeUtc = new DateTime(2038, 01, 19, 03, 14, 07, DateTimeKind.Utc);
private static long _unixTimestamp = 2147483647L;

[Fact]
public void Should_Convert_from_DateTime_to_UnixTime()
{
long result = _netDateTimeUtc.ToUnixTimeSeconds();
Assert.Equal(result, _unixTimestamp);
}

[Fact]
public void Should_Convert_from_UnixTime_to_DateTime()
{
DateTime result = _unixTimestamp.ToDateTiemUtc();
Assert.Equal(result, _netDateTimeUtc);
}
}
}
7 changes: 1 addition & 6 deletions test/JwtDnxTests/project.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
{
"version": "1.0.0-*",
"description": "JwtDnxTests Class Library",
"authors": [ "ax" ],
"tags": [ "" ],
"projectUrl": "",
"licenseUrl": "",
"dependencies": {
"FluentAssertions": "4.1.1",
"JwtDnx": "1.0.0-*",
"JwtDnx": "1.0.1-*",
"xunit": "2.1.0",
"xunit.runner.dnx": "2.1.0-rc1-build204"
},
Expand Down

0 comments on commit bf57ba3

Please sign in to comment.