Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
johnsheehan committed Jun 19, 2011
0 parents commit a0e3f33
Show file tree
Hide file tree
Showing 22 changed files with 33,157 additions and 0 deletions.
30 changes: 30 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@

#ignore thumbnails created by windows
Thumbs.db
#Ignore files build by Visual Studio
*.obj
*.exe
*.pdb
*.user
*.aps
*.pch
*.vspscc
*_i.c
*_p.c
*.ncb
*.suo
*.tlb
*.tlh
*.bak
*.cache
*.ilk
*.log
[Bb]in
[Dd]ebug*/
*.lib
*.sbr
obj/
[Rr]elease*/
_ReSharper*/
[Tt]est[Rr]esult*
download/
15 changes: 15 additions & 0 deletions JWT.nuspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<package>
<metadata>
<id>JWT</id>
<version>1.0</version>
<authors>John Sheehan</authors>
<description>JWT (JSON Web Token) Implementation for .NET (Public Domain)</description>
<language>en-US</language>
<projectUrl>http://github.com/johnsheehan/jwt</projectUrl>
<tags>jwt json</tags>
<dependencies>
<dependency id="JSON.NET" />
</dependencies>
</metadata>
</package>
20 changes: 20 additions & 0 deletions JWT.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JWT", "JWT\JWT.csproj", "{A80B51B8-DDF6-4026-98A4-B59653E50B38}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A80B51B8-DDF6-4026-98A4-B59653E50B38}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A80B51B8-DDF6-4026-98A4-B59653E50B38}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A80B51B8-DDF6-4026-98A4-B59653E50B38}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A80B51B8-DDF6-4026-98A4-B59653E50B38}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
123 changes: 123 additions & 0 deletions JWT/JWT.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace JWT
{
public enum JwtHashAlgorithm
{
HS256,
HS384,
HS512
}

public class JWT
{
private static Dictionary<JwtHashAlgorithm, Func<byte[], byte[], byte[]>> HashAlgorithms;

static JWT()
{
HashAlgorithms = new Dictionary<JwtHashAlgorithm, Func<byte[], byte[], byte[]>>
{
{ JwtHashAlgorithm.HS256, (key, value) => { using (var sha = new HMACSHA256(key)) { return sha.ComputeHash(value); } } },
{ JwtHashAlgorithm.HS384, (key, value) => { using (var sha = new HMACSHA384(key)) { return sha.ComputeHash(value); } } },
{ JwtHashAlgorithm.HS512, (key, value) => { using (var sha = new HMACSHA512(key)) { return sha.ComputeHash(value); } } }
};
}

public static string Encode(object payload, string key, JwtHashAlgorithm algorithm)
{
var segments = new List<string>();
var header = new { typ = "JWT", alg = algorithm.ToString() };

segments.Add(Base64UrlEncode(JsonConvert.SerializeObject(header, Formatting.Indented)));
segments.Add(Base64UrlEncode(JsonConvert.SerializeObject(payload, Formatting.Indented)));

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

var bytesToSign = Encoding.UTF8.GetBytes(stringToSign);
var keyBytes = Encoding.UTF8.GetBytes(key);

var signature = HashAlgorithms[algorithm](keyBytes, bytesToSign);
segments.Add(Base64UrlEncode(Encoding.UTF8.GetString(signature)));

return string.Join(".", segments.ToArray());
}

public static string Decode(string token, string key)
{
return Decode(token, key, true);
}

public static string Decode(string token, string key, bool verify)
{
var parts = token.Split('.');
var header = Encoding.UTF8.GetString(Base64UrlDecode(parts[0]));
var payload = Encoding.UTF8.GetString(Base64UrlDecode(parts[1]));
var crypto = Base64UrlDecode(parts[2]);

var json = new JsonSerializer();

var headerData = JObject.Parse(header);
var payloadData = JObject.Parse(payload);

if (verify)
{
var bytesToSign = Encoding.UTF8.GetBytes(string.Concat(header, ".", payload));
var keyBytes = Encoding.UTF8.GetBytes(key);
var algorithm = (string)headerData["alg"];

var signature = HashAlgorithms[GetHashAlgorithm(algorithm)](keyBytes, bytesToSign);

if (crypto != signature)
{
throw new ApplicationException("Invalid signature");
}
}

return payloadData.ToString();
}

private static JwtHashAlgorithm GetHashAlgorithm(string algorithm)
{
switch (algorithm)
{
case "HS256": return JwtHashAlgorithm.HS256;
case "HS384": return JwtHashAlgorithm.HS384;
case "HS512": return JwtHashAlgorithm.HS512;
default: throw new InvalidOperationException("Algorithm not supported.");
}
}

// from JWT spec
public static string Base64UrlEncode(string input)
{
var inputBytes = Encoding.UTF8.GetBytes(input);
var output = Convert.ToBase64String(inputBytes);
output = output.Split('=')[0]; // Remove any trailing '='s
output = output.Replace('+', '-'); // 62nd char of encoding
output = output.Replace('/', '_'); // 63rd char of encoding
return output;
}

// from JWT spec
public static byte[] Base64UrlDecode(string input)
{
var output = input;
output = output.Replace('-', '+'); // 62nd char of encoding
output = output.Replace('_', '/'); // 63rd char of encoding
switch (output.Length % 4) // Pad with trailing '='s
{
case 0: break; // No pad chars in this case
case 2: output += "=="; break; // Two pad chars
case 3: output += "="; break; // One pad char
default: throw new System.Exception("Illegal base64url string!");
}
return Convert.FromBase64String(output); // Standard base64 decoder
}
}

}
60 changes: 60 additions & 0 deletions JWT/JWT.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{A80B51B8-DDF6-4026-98A4-B59653E50B38}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>JWT</RootNamespace>
<AssemblyName>JWT</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json.Net35">
<HintPath>..\packages\Newtonsoft.Json.4.0.2\lib\net35\Newtonsoft.Json.Net35.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="JWT.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
36 changes: 36 additions & 0 deletions JWT/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("JWT")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("JWT")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("745e649e-588d-4e6d-81ce-1d2c39c24b0a")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
4 changes: 4 additions & 0 deletions JWT/packages.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="4.0.2" />
</packages>
13 changes: 13 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
JWT for .NET
Written by John Sheehan
(http://john-sheehan.com)

This work is public domain.
"The person who associated a work with this document has
dedicated the work to the Commons by waiving all of his
or her rights to the work worldwide under copyright law
and all related or neighboring legal rights he or she
had in the work, to the extent allowable by law."

For more information, please visit:
http://creativecommons.org/publicdomain/zero/1.0/
56 changes: 56 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
This is the next version of https://github.com/johnsheehan/TwilioApi. There are minor breaking changes in the REST API wrapper. The current state of this project is 'Release Candidate' and there might be bugs. Please report any using the issue tracker.

<hr />

# Twilio REST API and TwiML Libraries for .NET, ASP.NET, ASP.NET MVC and WebMatrix

Twilio provides a simple HTTP-based API for sending and receiving phone calls and text messages. Learn more at [http://www.twilio.com][0]

## [Twilio REST API Documentation][1]
## [Twilio TwiML Documentation][2]
## [.NET Library Documentation][3] (in progress)

### Sample Usage

using Twilio;
var twilio = new TwilioClient("accountSid", "authToken");
var call = twilio.InitiateOutboundCall("+1123456790", "+15555551212", "http://example.com/handleCall");
var msg = twilio.SendSmsMessage("+15555551212", "+11234567890", "Can you believe it's this easy to send an SMS?!");

### Silverlight/Windows Phone 7/Asynchronous Requests Sample

using Twilio;
var twilio = new TwilioClient("accountSid", "authToken");
twilio.InitiateOutboundCall("+1123456790", "+15555551212", "http://example.com/handleCall", (call) => {
// Console.WriteLog(call.Sid);
});

twilio.SendSmsMessage("+15555551212", "+11234567890", "Hello!", (msg) => {
// Console.WriteLine(msg.Sid);
});

### TwiML Generation with ASP.NET Sample

var response = new TwilioResponse();
response.Say("Hello Monkey");
response.Play("http://demo.twilio.com/hellomonkey/monkey.mp3");
response.BeginGather(new { numDigits = 1, action = "hello-monkey-handle-key.php", method = "POST" });
response.Say("To speak to a real monkey, press 1. Press 2 to record your own monkey howl. Press any other key to start over.");
response.EndGather();

// ASP.NET MVC when controller inherits from TwilioController
return TwiML(response);

// ASP.NET MVC regular controller
return new TwiMLResult(response);

// ASP.NET Webforms
var doc = response.ToXDocument();
Response.ContentType = "application/xml";
doc.Save(Response.Output);


[0]: http://www.twilio.com
[1]: http://www.twilio.com/docs/api/rest
[2]: http://www.twilio.com/docs/api/twiml
[3]: https://github.com/johnsheehan/Twilio/wiki
11 changes: 11 additions & 0 deletions package.cmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
if not exist download mkdir download
if not exist download\package mkdir download\package
if not exist download\package\lib mkdir download\package\lib
if not exist download\package\lib\3.5 mkdir download\package\lib\3.5

copy JWT\bin\Release\*.dll download
copy LICENSE.txt download

copy JWT\bin\Release\JWT.dll download\package\lib\3.5\

tools\nuget.exe pack JWT.nuspec -b download\package -o download
Binary file not shown.
Binary file not shown.
Loading

0 comments on commit a0e3f33

Please sign in to comment.