-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjwt.prw
112 lines (78 loc) · 2.61 KB
/
jwt.prw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#Include "Protheus.ch"
#Define ALGORITHMS {{'SHA256', 5}, {'SHA512', 7}}
/*/{Protheus.doc} Jwt
JsonWebToken for Protheus using ADVPL
@author Lucas Fidélis
@since 02/11/2021
@version P12
/*/
Class Jwt
Data cSecret
Data cAlgorithm
Data nAlgorithm
Method New() Constructor
Method Sign()
Method Verify()
EndClass
/*/{Protheus.doc} New
Constructor Method
@author Lucas Fidélis
@since 02/11/2021
@version P12
@param cSecret, String, Secret Key that will be used to generate the hash by HMAC
@return Self
/*/
Method New(cSecret, cAlgorithm) Class Jwt
Local nPos := 0
Default cAlgorithm := 'SHA256'
nPos := AScan(ALGORITHMS, { |x| x[1] == cAlgorithm})
If nPos == 0
UserException('Algorithm not found')
EndIf
::cAlgorithm := ALGORITHMS[nPos][1]
::nAlgorithm := ALGORITHMS[nPos][2]
::cSecret := cSecret
Return Self
/*/{Protheus.doc} Sign
Returns a JsonWebToken as string
@author Lucas Fidélis
@since 02/11/2021
@version P12
@param oPayload, Object, An object from JsonObject
@return cToken, String, A new JsonWebToken
/*/
Method Sign(oPayload) class Jwt
Local cToken, cHeader, cPayload, cSign
Local oHeader
oHeader := JsonObject():New()
oHeader["typ"] := "JWT"
oHeader["alg"] := ::cAlgorithm
cHeader := StrTran(Encode64(oHeader:toJson()), "=", "")
cPayload := StrTran(Encode64(oPayload:toJson()), "=", "")
cSign := StrTran(Encode64(HMAC(cHeader + '.' + cPayload, ::cSecret, ::nAlgorithm)), "=", "")
cToken := cHeader+"."+cPayload+"."+cSign
Return cToken
/*/{Protheus.doc} Verify
Returns if JsonWebToken is valid. If JsonWebToken is true and the param oPay is provided, oPay will be populated
with a JsonObject
@author Lucas Fidélis
@since 02/11/2021
@version P12
@param cToken, String, A JsonWebToken that will be validated
oPay, Object, An object from JsonObject provided by reference
@return lValid, Boolean, If JsonWebToken provided is valid
oPay, Object, Object provided by reference that will be populated with the informations from payload as JsonObject
/*/
Method Verify(cToken, oPay) class Jwt
Local aParts := StrTokArr(cToken, '.')
Local cHeader := aParts[1]
Local cPayload := aParts[2]
Local cTokenValid
cSign := StrTran(Encode64(HMAC(cHeader + '.' + cPayload, ::cSecret, ::nAlgorithm)), "=", "")
cTokenValid := cHeader+"."+cPayload+"."+cSign
lValid := cToken == cTokenValid
If lValid
cPay := Decode64(cPayload)
oPay:FromJson(cPay)
EndIf
Return lValid