Using JwtIssuer from Core Package - datvm/JwtSharp GitHub Wiki

Instantiate and Options

You can instantiate a JwtIssuer with options by using a builder, or create new JwtIssuerOptions object by yourself.

            var jwtIssuer = new JwtIssuer(options =>
            {
                options.Audience = "Your Audience";
                options.Issuer = "Your Issuer";
                options.SecurityKey = "YOUR SECURITY KEY";

                // If you want to have expiration time, set the number of second
                // Default is null, meaning the token will never be expired
                options.ExpireSeconds = 1800;

                // Optionally choose Hash Algorithm
                // Default is SecurityAlgorithms.HmacSha256
                options.SecurityAlgorithm = SecurityAlgorithms.Sha512;
            });

Issuing tokens

Use the overloads of IssueToken to generate JWT tokens:

Using string pairs:

This is the desired overload for quick usage. Simply put the string pairs next to each other (n-th token will have 2n-th string as Type and 2n+1-th string as Value):

            var token = jwtIssuer.IssueToken(
                "username", "some-user",
                "role", "admin",
                "email", "[email protected]"
            );

Using a Claim Collection:

Alternatively, you can simply put in all the Claims:

            var token = jwtIssuer.IssueToken(new Claim[]
            {
                new Claim("username", "some-user"),
                new Claim("role", "admin"),
                new Claim("email", "[email protected]"),
            });

You can also use KeyValuePair<string, string> instead.

Custom Expiration Time

Since v1.1, you can also specify expiration time instead of the default set (you can set it to null for never expired token:

            var token = jwtIssuer.IssueToken(new Claim[]
            {
                new Claim("username", "some-user"),
                new Claim("role", "admin"),
                new Claim("email", "[email protected]"),
            }, DateTime.UtcNow.AddDays(3));

Read a JWT Token

With the same JwtIssuer, you can read a JWT string token using ReadToken method:

var decodedToken = jwtIssuer.ReadToken(token);

IMPORTANT: This method does NOT validate a token with Signing Certificate.

Validate a JWT Token

To validate (and get the ClaimsPrincipal) from a token, use GetPrincipal method instead:

            var principal = jwtIssuer.GetPrincipal(token);
            if (!principal.Identity.IsAuthenticated) { throw new Exception("Unauthorized!"); }
            if (!principal.Claims.Any(q => q.Type == "admin" && q.Value == "True")) { throw new Exception("Forbidden!"); }