Skip to content
Kingcean edited this page Apr 16, 2019 · 5 revisions

OAuth

OAuth 2.0 supports.

In Trivial.Security namespace of Trivial.dll library.

Authentication

You can use following additional models for OAuth and app key.

  • TokenInfo The access token and other properties.
  • AppAccessingKey The app identifier and secret key.

You can access the resources required access token authentication by using an instance of the OAuthClient class with the AppAccessingKey instance, scope and authorization URI. Following is an example for WNS.

// Inialize a new instance of OAuth client
// with client identifier, client secret, authorization URI and scope.
var oauth = new OAuthClient(
    "client_id",        // Client ID.
    "client_secret",    // Client secret.
    new Uri("https://login.live.com/accesstoken.srf"),
    "notify.windows.com");

// Get access token.
await oauth.ResolveTokenAsync(new ClientTokenRequestBody());

// Then you can create the JSON HTTP web client when you need,
// And it will set the access token into the authorization header.
var httpClient = oauth.Create<ResponseBody>();

// And, of course, you can get the access token by following property.
var token = oauth.Token;

JWT

You can create a JSON web token to get an authorization header in HTTP request by initializing a new instance of the JsonWebToken class.

// Create a hash signature provider.
var sign = HashSignatureProvider.CreateHS512("a secret string");

// Create a payload.
// So you need a class as the JWT payload.
// You can also inherit from JsonWebTokenPayload class if you need which contains some useful fields.
// Suppose we have a class Model here to use.
var model = new Model();

// Create a JWT instance.
var jwt = new JsonWebToken<Model>(new Model(), sign);

// Get the JWT string encoded.
var jwtStr = jwt.ToEncodedString();

// Get authenticiation header value.
var header = jwt.ToAuthenticationHeaderValue();

// Parse.
var jwtSame = JsonWebToken<Model>.Parse(jwtStr, sign); // jwtSame.ToEncodedString() == jwtStr

And you can also parse a JWT string by following way.

var parser = new JsonWebToken<Model>.Parser(jwtStr);

// Verify.
var isVerified = parser.Verify(sign);

// Get payload model.
var payload = parser.GetPayload();

// Convert to a JWT instance.
var jwt = parser.ToToken(sign, true);

Following are the signature providers. You can call one of these function and pass the secret as a parameter.

Algorithm Name Function Name
HS512 HashSignatureProvider.CreateHS512
HS384 HashSignatureProvider.CreateHS384
HS256 HashSignatureProvider.CreateHS256
RS512 RSASignatureProvider.CreateRS512
RS384 RSASignatureProvider.CreateRS384
RS256 RSASignatureProvider.CreateRS256

You can also initialize a new instance of the KeyedSignatureProvider class for your own signature provider.

See JWT.IO to test JWT or get details about it.

You can’t perform that action at this time.