Skip to content

Instantly share code, notes, and snippets.

@pdoran
Created July 19, 2014 01:48
Show Gist options
  • Save pdoran/09beb1744d82dbdfc5d2 to your computer and use it in GitHub Desktop.
Save pdoran/09beb1744d82dbdfc5d2 to your computer and use it in GitHub Desktop.
Utility to generate an Oauthtoken with DotNetOAuth given a certificate public/private key pair
public class OAuthTokenUtility {
private readonly RSACryptoServiceProvider _PublicProvider;
private readonly RSACryptoServiceProvider _PrivateProvider;
public OAuthTokenUtility(X509Certificate2 certificate) {
_PublicProvider = (RSACryptoServiceProvider)certificate.PublicKey.Key;
_PrivateProvider = (RSACryptoServiceProvider)Certificate.PrivateKey;
}
public string Token(string username, double numberOfMinutesToExpireIn, IEnumerable<string> tokens) {
var authServerAccessToken = new AuthorizationServerAccessToken();
authServerAccessToken.Lifetime = TimeSpan.FromMinutes(2);
authServerAccessToken.ResourceServerEncryptionKey = _PublicProvider;
authServerAccessToken.AccessTokenSigningKey = _PrivateProvider;
var result = new AccessTokenResult(authServerAccessToken);
var accessToken = result.AccessToken;
var applyAuthorizationMethod = accessToken.GetType()
.GetMethods(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
.FirstOrDefault(f => f.Name == "ApplyAuthorization" && f.GetParameters().Count() == 3);
var serializeMethod = accessToken.GetType()
.GetMethod("Serialize", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
applyAuthorizationMethod.Invoke(accessToken, new Object[] { tokens, username, TimeSpan.FromMinutes(numberOfMinutesToExpireIn) });
var output = serializeMethod.Invoke(accessToken, new Object[] { }) as string;
return output;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment