diff --git a/README.md b/README.md index b8755b8..c186658 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ A JWT implementation in Classic ASP, currently only supports `JWTEncode(dictiona ```asp <% -Dim sKey, dAttributes, sToken +Dim sKey, dAttributes, sToken, decodedPayload, isValidJWT sKey = "Shared Secret" Set dAttributes=Server.CreateObject("Scripting.Dictionary") @@ -19,6 +19,12 @@ dAttributes.Add "name", "Roger" dAttributes.Add "email", "roger@example.com" sToken = JWTEncode(dAttributes, sKey) + +' Decode JWT token string and get payload. (WARNING : Not verify) +decodedPayload = JWTDecode(sToken) + +' Verify JWT String. (Returns Boolean) +isValidJWT = JWTVerify(sToken, sKey) %> ``` diff --git a/jwt.asp b/jwt.asp index 0ce921d..4c3c441 100644 --- a/jwt.asp +++ b/jwt.asp @@ -6,7 +6,12 @@ Function JWTEncode(dPayload, sSecret) Dim sPayload, sHeader, sBase64Payload, sBase64Header Dim sSignature, sToken - sPayload = DictionaryToJSONString(dPayload) + If Typename(dPayload) = "Dictionary" Then + sPayload = DictionaryToJSONString(dPayload) + Else + sPayload = dPayload + End If + sHeader = JWTHeaderDictionary() sBase64Payload = SafeBase64Encode(sPayload) @@ -42,4 +47,26 @@ Function JWTHeaderDictionary() JWTHeaderDictionary = DictionaryToJSONString(dOut) End Function + +' Returns decoded payload (not verify) +Function JWTDecode(token) + Dim tokenSplited, sPayload + tokenSplited = Split(token, ".") + If UBound(tokenSplited) <> 2 Then + JWTDecode = "Invalid token" + Else + sPayload = tokenSplited(1) + sPayload = SafeBase64ToBase64(sPayload) + JWTDecode = Base64Decode(sPayload) + End If +End Function + +' Returns if token is valid +Function JWTVerify(token, sKey) + Dim jsonPayload, reEncodingToken, tokenPayload + tokenPayload = JWTDecode(token) + reEncodingToken = JWTEncode(tokenPayload, sKey) + + JWTVerify = (token = reEncodingToken) +End Function %> diff --git a/utils.asp b/utils.asp index 16438aa..5a3a525 100644 --- a/utils.asp +++ b/utils.asp @@ -24,6 +24,17 @@ Function Base64ToSafeBase64(sIn) Base64ToSafeBase64 = sOut End Function +' change safe base64 to original base64 +Function SafeBase64ToBase64(sIn) + Dim removedEqualityLen + removedEqualityLen = 4 - Len(sIn) mod 4 + If removedEqualityLen = 4 Then removedEqualityLen = 0 + sOut = Replace(sIn,"-","+") + sOut = Replace(sOut,"_","/") + sOut = sOut & Replace(Space(removedEqualityLen)," ","=") + SafeBase64ToBase64 = sOut +End Function + ' Converts an ASP dictionary to a JSON string Function DictionaryToJSONString(dDictionary) Set oJSONpayload = New aspJSON