Bringing SWT Support back to Thinktecture IdentityModel

When Microsoft released the JWT library, I thought that’s a good opportunity to remove the SWT support from IdentityModel. But it turns out, there are still scenarios for SWT – so I refreshed my old code and added the SWT token and token handler back.

Note: I am now using the NamedKeyIssuerTokenResolver from the JWT library which is very useful here and allowed me to remove a lot of my custom code.

Here’s how it works – Creating a token:

public SimpleWebToken CreateToken(byte[] key)

{

    var descripter = new SecurityTokenDescriptor

    {

        TokenIssuerName = http://issuer,

        AppliesToAddress = http://audience,

 

        Lifetime = new Lifetime(DateTime.Now, DateTime.Now.AddMinutes(5)),

        Subject = new ClaimsIdentity(GetClaims()),

 

        SigningCredentials = new HmacSigningCredentials(key),

    };

 

    var handler = new SimpleWebTokenHandler();

    return handler.CreateToken(descripter) as SimpleWebToken;

}

 

Validating a token

private static void ValidateSwtToken(string tokenString)
{
    var configuration = new SecurityTokenHandlerConfiguration();
    var validationKey = new InMemorySymmetricSecurityKey(
Convert.FromBase64String(Constants.IdSrv
.SigningKey));
 
    // audience validation
    configuration.AudienceRestriction.AllowedAudienceUris.Add(
new Uri(Constants.Realm));
 
    // signature & issuer validation
    var resolverTable = new Dictionary<string, IList<SecurityKey>>
    {
        { Constants.IdSrv.IssuerUri, new SecurityKey[] { validationKey } }
    };
 
    configuration.IssuerTokenResolver = 
new NamedKeyIssuerTokenResolver(resolverTable);
 
    var handler = new SimpleWebTokenHandler();
    handler.Configuration = configuration;
 
    var token = handler.ReadToken(tokenString);
    var ids = handler.ValidateToken(token);
 
    "\n\nValidated Claims:".ConsoleYellow();
    foreach (var claim in ids.First().Claims)
    {
        Console.WriteLine("{0}\n {1}\n", claim.Type, claim.Value);
    }
}

 

This entry was posted in IdentityModel, IdentityServer. Bookmark the permalink.

One Response to Bringing SWT Support back to Thinktecture IdentityModel

  1. Pingback: Using IdentityServer to issue tokens for Windows Server ServiceBus | www.leastprivilege.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s