public JWTToken GetToken(TPayload payload) { if (payload == null) { throw new JWTExceptions.JWTPayloadNullExceptions("Payload is null"); } this.Payload = payload; string payloadJson = JWTTokenHelpers.JSONSerialize(payload); string headerJson = JWTTokenHelpers.JSONSerialize(Header); string payloadEncoded = JWTTokenHelpers.GetBase64URLEncoded(payloadJson); string headerEncoded = JWTTokenHelpers.GetBase64URLEncoded(headerJson); string signature = JWTTokenHelpers.CreateSignature(headerEncoded, payloadEncoded, Algorithm); signature = JWTTokenHelpers.GetBase64URLEncoded(signature); string token = headerEncoded + "." + payloadEncoded + "." + signature; return(new JWTToken() { Token = token, Header = Header, Payload = payload }); }
internal static JWTToken isValid <TPayload>(string token, KeyedHashAlgorithm algorithm, JWTAcceptedValues values) where TPayload : JWTPayload { List <string> tokenParts = new List <string>(); try { tokenParts = token.Split('.').ToList(); } catch { throw new JWTExceptions.JWTSplitException("Token split exception"); } if (tokenParts.Count != 3) { throw new JWTExceptions.JWTSplitException("Token doesnot have 3 parts"); } string currentSignature = ""; try { currentSignature = JWTTokenHelpers.CreateSignature(tokenParts[0], tokenParts[1], algorithm); currentSignature = GetBase64URLEncoded(currentSignature); string oldSignature = tokenParts[2]; if (oldSignature == null || !oldSignature.Equals(currentSignature)) { throw new JWTExceptions.JWTSignatureException("Signature invalid"); } } catch { throw new JWTExceptions.JWTSignatureException("Signature invalid"); } try { for (int i = 0; i < 2; i++) { tokenParts[i] = GetBase64URLDecoded(tokenParts[i]); } } catch { throw new JWTExceptions.JWTDecodingExceptions("Token parts are not decodable"); } JWTHeader header = new JWTHeader(); TPayload payload; try { header = JSONDesialize <JWTHeader>(tokenParts[0]); payload = JSONDesialize <TPayload>(tokenParts[1]); } catch { throw new JWTExceptions.JWTDeserializeException("Data not parsable"); } if (payload != null) { if (payload.ExpiryTime.Subtract(DateTime.Now) > values.ExpiryDuration) { throw new JWTExceptions.JWTExpiredException("JWT expired"); } else if (payload.IpAddress == null || !payload.IpAddress.Equals(values.IpAddress)) { throw new JWTExceptions.JWTIpAddressException("IP Address mismatch"); } else if (payload.Audience == null || !payload.Audience.Equals(values.Audience)) { throw new JWTExceptions.JWTIncorrectAudienceException("Audience incorrect"); } else if (payload.Issuer == null || !payload.Issuer.Equals(values.Issuer)) { throw new JWTExceptions.JWTIssuerIncorrectException("Issuer mismatch"); } else { return(new JWTToken() { Header = header, Payload = payload, Token = token }); } } else { throw new JWTExceptions.JWTPayloadEmptyException("Payload null"); } }