public static JwtPayload DecodeToken(string token, string secret, out bool validated) { var jwtPayload = new JwtPayload(); var segments = token.Split('.'); var invalidToken = segments.Length != 3; if (!invalidToken) { try { jwtPayload = JsonConvert.DeserializeObject( Encoding.UTF8.GetString(Base64Decode(segments[1])), typeof(JwtPayload)); var rawSignature = segments[0] + '.' + segments[1]; validated = Verify(rawSignature, secret, segments[2]); } catch (Exception) { validated = false; } } else { validated = false; } return jwtPayload; }
public static string EncodeToken(JwtPayload jwtPayload, string secret) { const string algorithm = "HMAC256"; var header = new JwtHeader { typ = "JWT", alg = algorithm }; var jwt = Base64Encode(JsonConvert.SerializeObject(header)) + "." + Base64Encode(JsonConvert.SerializeObject(jwtPayload)); jwt += "." + Sign(jwt, secret); return jwt; }