Quantcast
Channel: IdentityModel – leastprivilege.com
Viewing all articles
Browse latest Browse all 204

Bringing SWT Support back to Thinktecture IdentityModel

$
0
0

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);
    }
}

 


Filed under: IdentityModel, IdentityServer

Viewing all articles
Browse latest Browse all 204