This repository was archived by the owner on Jul 26, 2025. It is now read-only.
forked from zaproxy/community-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaintain-jwt.js
More file actions
71 lines (59 loc) · 2.44 KB
/
Copy pathmaintain-jwt.js
File metadata and controls
71 lines (59 loc) · 2.44 KB
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
/*exported sendingRequest, responseReceived*/
// This script looks for JWT tokens in responses, the current one
// via ScriptVars, and updates all requests adding an Authorization header
// bearer value based on the tracked JWT.
// Logging with the script name is super helpful!
function logger() {
print('[' + this['zap.script.name'] + '] ' + arguments[0]);
}
var HttpSender = Java.type('org.parosproxy.paros.network.HttpSender');
var ScriptVars = Java.type('org.zaproxy.zap.extension.script.ScriptVars');
var HtmlParameter = Java.type('org.parosproxy.paros.network.HtmlParameter')
var COOKIE_TYPE = org.parosproxy.paros.network.HtmlParameter.Type.cookie;
function sendingRequest(msg, initiator, helper) {
if (initiator === HttpSender.AUTHENTICATION_INITIATOR) {
logger("Trying to auth")
return msg;
}
var token = ScriptVars.getGlobalVar("jwt-token")
if (!token) {return;}
var cookie = new HtmlParameter(COOKIE_TYPE, "token", token);
msg.getRequestHeader().getCookieParams().add(cookie);
// For all non-authentication requests we want to include the authorization header
logger("Added authorization token " + token.slice(0, 20) + " ... ")
msg.getRequestHeader().setHeader('Authorization', 'Bearer ' + token);
return msg;
}
function responseReceived(msg, initiator, helper) {
var resbody = msg.getResponseBody().toString()
var resheaders = msg.getResponseHeader()
if (initiator !== HttpSender.AUTHENTICATION_INITIATOR) {
var token = ScriptVars.getGlobalVar("jwt-token");
if (!token) {return;}
var headers = msg.getRequestHeader();
var cookies = headers.getCookieParams();
var cookie = new HtmlParameter(COOKIE_TYPE, "token", token);
if (cookies.contains(cookie)) {return;}
msg.getResponseHeader().setHeader('Set-Cookie', 'token=' + token + '; Path=/;');
return;
}
logger("Handling auth response")
if (resheaders.getStatusCode() > 299) {
logger("Auth failed")
return;
}
// Is response JSON? @todo check content-type
if (resbody[0] !== '{') {return;}
try {
var data = JSON.parse(resbody);
} catch (e) {
return;
}
// If auth request was not succesful move on
if (!data['authentication']) {return;}
// @todo abstract away to be configureable
var token = data["authentication"]["token"]
logger("Capturing token for JWT\n" + token)
ScriptVars.setGlobalVar("jwt-token", token)
msg.getResponseHeader().setHeader('Set-Cookie', 'token=' + token + '; Path=/;');
}