forked from koajs/jwt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest-server.js
54 lines (45 loc) · 1.32 KB
/
test-server.js
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
var JWT = require('jsonwebtoken');
var koa = require('koa');
var jwt = require('.');
var profile = {
id: 123
};
var token = JWT.sign(profile, 'secret', { expiresInMinutes: 60*5 });
console.log('Starting koa-jwt test server on http://localhost:3000/');
console.log('');
console.log('You can test the server by issuing curl commands like the following:');
console.log('')
console.log(' curl http://localhost:3000/public/foo # should succeed');
console.log(' curl http://localhost:3000/api/foo # should fail');
console.log(' curl -H "Authorization: Bearer ' + token + '" http://localhost:3000/api/foo # should succeed');
console.log('')
var app = koa();
// Custom 401 handling
app.use(function *(next){
try {
yield next;
} catch (err) {
if (401 == err.status) {
this.status = 401;
this.body = '401 Unauthorized - Protected resource, use Authorization header to get access\n';
} else {
throw err;
}
}
});
// Unprotected middleware
app.use(function *(next){
if (this.url.match(/^\/public/)) {
this.body = 'unprotected\n';
} else {
yield next;
}
});
// Middleware below this line is only reached if JWT token is valid
app.use(jwt({ secret: 'secret' }));
app.use(function *(){
if (this.url.match(/^\/api/)) {
this.body = 'protected\n';
}
});
app.listen(3000);