Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/TokenAuthExampleWebApplication/KeyContainer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Threading.Tasks;

namespace TokenAuthExampleWebApplication
{
public class KeyContainer
{
public static RSAParameters GetKeyFromContainer(string containerName)
{
CspParameters cp = new CspParameters { KeyContainerName = containerName, };
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, cp);
RSAParameters rsaKeyInfo = rsa.ExportParameters(true);
return rsaKeyInfo;

}
}
}
17 changes: 5 additions & 12 deletions src/TokenAuthExampleWebApplication/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,25 +25,18 @@ public Startup(IHostingEnvironment env)

public void ConfigureServices(IServiceCollection services)
{
// *** CHANGE THIS FOR PRODUCTION USE ***
// Here, we're generating a random key to sign tokens - obviously this means
// that each time the app is started the key will change, and multiple servers
// all have different keys. This should be changed to load a key from a file
// securely delivered to your application, controlled by configuration.
//
// See the RSAKeyUtils.GetKeyParameters method for an examle of loading from
// a JSON file.
RSAParameters keyParams = RSAKeyUtils.GetRandomKey();
// Fetching key from KeyContainer, if the key does not exist, we create it.
var keyFromContainer = KeyContainer.GetKeyFromContainer("TokenAuthExample");

// Create the key, and a set of token options to record signing credentials
// using that key, along with the other parameters we will need in the
// token controlller.
key = new RsaSecurityKey(keyParams);

tokenOptions = new TokenAuthOptions()
{
Audience = TokenAudience,
Issuer = TokenIssuer,
SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature)
SigningCredentials = new SigningCredentials(keyFromContainer, SecurityAlgorithms.RsaSha256Signature)
};

// Save the token options into an instance so they're accessible to the
Expand All @@ -54,7 +47,7 @@ public void ConfigureServices(IServiceCollection services)
services.AddAuthorization(auth =>
{
auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser().Build());
});

Expand Down