/// <summary> /// This constructor should be used to load and incoming token. /// </summary> /// <param name="token">The compact serialized token.</param> /// <param name="secret">The secret to validate the token.</param> /// <param name="validateSignature">A boolean value that indicates when token should be validated with the secret.</param> /// <param name="supportNoneAlgo">This property specifies whether the none algorithm should be supported. As this is a security risk, it has to be explicitly set to accept.</param> public JwtToken(string token, byte[] secret, bool validateSignature = true, bool supportNoneAlgo = false) { mIncoming = new JwtRoot(token); Header = new JOSEHeader(mIncoming.JoseHeader); if (!string.Equals(Header.Type, "JWT", StringComparison.InvariantCultureIgnoreCase)) { throw new JwtTokenStructureInvalidException("The JWT declaration is not in the JOSE Header"); } //Check that the algorithm is supported. var algo = Header.SupportedAlgorithm; if (algo == JwtHashAlgorithm.None && !supportNoneAlgo) { throw new JwtAlgorithmNoneNotAllowedException(); } Claims = new JwtClaims(JwtRoot.UTF8ToJSONConvert(mIncoming.Raw[1])); if (validateSignature && !JwtValidateIncoming(mIncoming, algo, secret)) { throw new JwtSignatureInvalidException(); } }
/// <summary> /// This is the default constructor for creating a new token. /// </summary> public JwtToken(JwtHashAlgorithm?algo = null) { Header = new JOSEHeader(); //Set the default settings. Header.SupportedAlgorithm = algo ?? JwtHashAlgorithm.HS256; Header.Type = "JWT"; //Set the empty claims. Claims = new JwtClaims(); }
/// <summary> /// This shortcuts sets the name using the Microsoft defined claim id. /// </summary> /// <param name="claims">The claims.</param> /// <param name="name">The name.</param> public static void ShortcutSetName(this JwtClaims claims, string name) { claims[ClaimsIdentity.DefaultNameClaimType] = name; }
/// <summary> /// This shortcuts the set role using the Microsoft defined claim id. /// </summary> /// <param name="claims">The claims.</param> /// <param name="role">The role id.</param> public static void ShortcutSetRole(this JwtClaims claims, string role) { claims[ClaimsIdentity.DefaultRoleClaimType] = role; }