-
Notifications
You must be signed in to change notification settings - Fork 6
/
iNat_PKCE_flow_example.html
316 lines (272 loc) · 11.6 KB
/
iNat_PKCE_flow_example.html
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="iNaturalist Single-Page App using PKCE OAuth flow and API v1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<title>iNaturalist Single-Page App using PKCE OAuth flow and API v1</title>
<!-- This example app is registered as #399 in iNaturalist:
https://www.inaturalist.org/oauth/applications/399
It does 3 things:
1. Gets access token via PKCE OAuth flow
2. Uses the result of #1 to get a JSON Web Token (JWT)
3. Uses the result of #2 to query the GET /user/me endpoint in the v1 API
If everything is successful, the page should ask you to log in via the iNaturalist website (if you're not already logged in), and then display your user login.
Other Notes:
1. The code for the PKCE flow will not work with Edge / IE.
2. This example hits only relatively safe endpoints. If you adapt this to hit endpoints like GET /observations, you may want to handle cases where someone could, say, include malicious code in observation descriptions and comments. Be safe out there!
//-->
<!--//
Much of the code that handles the PKCE oAuth flow here is adpated from
https://github.com/aaronpk/pkce-vanilla-js, with license details below:
MIT License
Copyright (c) 2019 Aaron Parecki
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
//-->
<style>
body { padding:0; margin:0; min-height:100vh; font-family: arial, sans-serif; }
@media(max-width:400px) { body { padding:10px; } }
.full-height { min-height:100vh; }
.flex-center { align-items:center; display:flex; justify-content:center; }
.content { max-width:400px; }
h2 { text-align:center; }
.code { font-family:"Courier New", "Courier", monospace; width:100%; padding:4px; border:1px #ccc solid; border-radius:4px; word-break:break-all; }
.hidden { display:none; }
</style>
<script>
//////////////////////////////////////////////////////////////////////
// GENERAL HELPER FUNCTIONS
// Make a POST request and parse the response as JSON
function sendPostRequest(url, params, success, error) {
var request = new XMLHttpRequest();
request.open('POST', url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onload = function() {
var body = {};
try {
body = JSON.parse(request.response);
} catch(e) {}
if(request.status == 200) {
success(request, body);
} else {
error(request, body);
}
}
request.onerror = function() {
error(request, {});
}
var body = Object.keys(params).map(key => key + '=' + params[key]).join('&');
request.send(body);
}
// Parse a query string into an object
function parseQueryString(string) {
if(string == "") { return {}; }
var segments = string.split("&").map(s => s.split("=") );
var queryString = {};
segments.forEach(s => queryString[s[0]] = s[1]);
return queryString;
}
//////////////////////////////////////////////////////////////////////
// PKCE HELPER FUNCTIONS
// Generate a secure random string using the browser crypto functions
function generateRandomString() {
var array = new Uint32Array(28);
window.crypto.getRandomValues(array);
return Array.from(array, dec => ('0' + dec.toString(16)).substr(-2)).join('');
}
// Calculate the SHA256 hash of the input text.
// Returns a promise that resolves to an ArrayBuffer
function sha256(plain) {
const encoder = new TextEncoder();
const data = encoder.encode(plain);
return window.crypto.subtle.digest('SHA-256', data);
}
// Base64-urlencodes the input string
function base64urlencode(str) {
// Convert the ArrayBuffer to string using Uint8 array to conver to what btoa accepts.
// btoa accepts chars only within ascii 0-255 and base64 encodes them.
// Then convert the base64 encoded to base64url encoded
// (replace + with -, replace / with _, trim trailing =)
return btoa(String.fromCharCode.apply(null, new Uint8Array(str)))
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
// Return the base64-urlencoded sha256 hash for the PKCE challenge
async function pkceChallengeFromVerifier(v) {
hashed = await sha256(v);
return base64urlencode(hashed);
}
</script>
</head>
<body>
<div class="flex-center full-height">
<div class="content">
<div id="login">
<a href="#" id="start">Click to Sign In</a>
</div>
<div id="token" class="hidden">
<h2>JSON Web Token</h2>
<div id="access_token" class="code"></div>
</div>
<div id="user" class="hidden">
<h2>iNaturalist User</h2>
<div id="user_id" class="code"></div>
</div>
<div id="error" class="hidden">
<h2>Error</h2>
<div id="error_details" class="code"></div>
</div>
</div>
</div>
<script>
//////////////////////////////////////////////////////////////////////
var urlbase_iNat = 'https://www.inaturalist.org';
var urlbase_iNat_v1 = 'https://api.inaturalist.org/v1';
var urlbase_app = 'https://jumear.github.io/stirfry/iNat_PKCE_flow_example.html';
let reqHeader = new Headers();
reqHeader.append('Content-Type','application/json');
// this section is only for testing purposes
// it allows you to skip all the steps needed to get a JWT, if you already have one.
// var testjwt = '';
// reqHeader.append('Authorization',('Bearer '+testjwt));
// fcoreapp();
// exit;
//////////////////////////////////////////////////////////////////////
// PKCE flow -- Configure application and authorization server details
var config = {
client_id: "23361deacac33d856d63ef2df2f43d01c6d163dcf3c0e61d8a8d33d8bc2d4c58",
redirect_uri: urlbase_app,
authorization_endpoint: urlbase_iNat+"/oauth/authorize",
token_endpoint: urlbase_iNat+"/oauth/token",
requested_scopes: "write"
};
//////////////////////////////////////////////////////////////////////
// OAUTH REQUEST
// Initiate the PKCE Auth Code flow when the link is clicked
document.getElementById("start").addEventListener("click", async function(e){
e.preventDefault();
// Create and store a random "state" value
var state = generateRandomString();
localStorage.setItem("pkce_state", state);
// Create and store a new PKCE code_verifier (the plaintext random secret)
var code_verifier = generateRandomString();
localStorage.setItem("pkce_code_verifier", code_verifier);
// Hash and base64-urlencode the secret to use as the challenge
var code_challenge = await pkceChallengeFromVerifier(code_verifier);
// Build the authorization URL
var url = config.authorization_endpoint
+ "?response_type=code"
+ "&client_id="+encodeURIComponent(config.client_id)
+ "&state="+encodeURIComponent(state)
+ "&scope="+encodeURIComponent(config.requested_scopes)
+ "&redirect_uri="+encodeURIComponent(config.redirect_uri)
+ "&code_challenge="+encodeURIComponent(code_challenge)
+ "&code_challenge_method=S256"
;
// Redirect to the authorization server
window.location = url;
});
//////////////////////////////////////////////////////////////////////
// OAUTH REDIRECT HANDLING
// Handle the redirect back from the authorization server and
// get an access token from the token endpoint
var q = parseQueryString(window.location.search.substring(1));
// Check if the server returned an error string
if(q.error) {
alert("Error returned from authorization server: "+q.error);
document.getElementById("error_details").innerText = q.error+"\n\n"+q.error_description;
document.getElementById("error").classList = "";
}
// If the server returned an authorization code, attempt to exchange it for an access token
if(q.code) {
// Verify state matches what we set at the beginning
if(localStorage.getItem("pkce_state") != q.state) {
alert("Invalid state");
} else {
// Exchange the authorization code for an access token
sendPostRequest(config.token_endpoint, {
grant_type: "authorization_code",
code: q.code,
client_id: config.client_id,
redirect_uri: config.redirect_uri,
code_verifier: localStorage.getItem("pkce_code_verifier")
}, function(request, body) {
// Replace the history entry to remove the auth code from the browser address bar
window.history.replaceState({}, null, config.redirect_uri); //"/");
// Initialize your application now that you have an access token.
fgetJWT(body.access_token)
.then((jwt)=> {
reqHeader.append('Authorization',('Bearer '+jwt));
fcoreapp();
});
}, function(request, error) {
// This could be an error response from the OAuth server, or an error because the
// request failed such as if the OAuth server doesn't allow CORS requests
document.getElementById("error_details").innerText = error.error+"\n\n"+error.error_description;
document.getElementById("error").classList = "";
});
}
// Clean these up since we don't need them anymore
localStorage.removeItem("pkce_state");
localStorage.removeItem("pkce_code_verifier");
}
function fgetJWT(accesstoken) {
var endpoint = {method:'GET',url:urlbase_iNat+'/users/api_token'};
var hdr = new Headers();
hdr.append('Content-Type','application/json');
hdr.append('Authorization',('Bearer '+accesstoken));
return fetch(endpoint.url, {
method: endpoint.method,
headers: hdr,
})
.then((response) => {
if (!response.ok) { throw new Error(response.status+' ('+response.statusText+') returned from '+response.url); };
return response.json();
})
.then((data) => {
return data.api_token;
})
.catch((err) => {
console.error(err.message);
});
};
function fcoreapp() {
// Remove login link
document.getElementById("login").classList = "hidden";
fgetuser()
.then((data) => {
document.getElementById("user_id").innerText = data.results[0].login;
document.getElementById("user").classList = "";
});
};
function fgetuser() {
var endpoint = {method:'GET',url:urlbase_iNat_v1+'/users/me'};
return fetch(endpoint.url, {
method: endpoint.method,
headers: reqHeader,
})
.then((response) => {
if (!response.ok) { throw new Error(response.status+' ('+response.statusText+') returned from '+response.url); };
return response.json();
})
.catch((err) => {
console.error(err.message);
});
};
</script>
</body>
</html>