Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
If you’re using the Windows Azure AppFabric Access Control Service (ACS) you’ve probably encountered a Simple Web Token (SWT) accessed via the Web Resource Authorization Protocol (WRAP). Doing this recently, I wanted to figure out when my token expired (so that I could cache it until a couple of minutes before expiry, improving my app's performance) – you might find this snippet useful if you want to figure out when a SWT token expires:
/// <summary>
/// Gets the UTC time that the specified token expires.
/// </summary>
/// <param name="token">An Access Token from the Access Control Service .</param>
/// <returns>The time that the token expires as a UTC DateTime.</returns>
public static DateTime GetExpiryTime(string token)
{
var swt = token.Substring("wrap_access_token=\"".Length, token.Length - ("wrap_access_token=\"".Length + 1));
var tokenValue = Uri.UnescapeDataString(swt);
var properties = (from prop in tokenValue.Split('&')
let pair = prop.Split(new[] { '=' }, 2)
select new { Name = pair[0], Value = pair[1] })
.ToDictionary(p => p.Name, p => p.Value);
var expiresOnUnixTicks = int.Parse(properties["ExpiresOn"]);
var epochStart = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc);
return epochStart.AddSeconds(expiresOnUnixTicks);
}
The code takes an access token from ACS (of the format wrap_access_token=”[Insert-SWT-Here]” ) and extracts the ‘ExpiresOn’ value from the SWT. According to the OAuth WRAP Spec, this is a Unix time (i.e., the number of seconds past January 1, 1970 at 12am) expressed as a UTC time. So, don’t forget that if you want to figure out when the token expires in your local time zone, you’ll need to convert it using the TimeZone type:
Console.WriteLine("Your auth token expires at {0}.", TimeZone.CurrentTimeZone.ToLocalTime(this.AuthTokenExpiry));
I hope this helps,
Will