-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkoa-auth-server.js
86 lines (74 loc) · 2.44 KB
/
koa-auth-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
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
'use strict'
const Koa = require('koa')
const cors = require('koa2-cors')
const Router = require('koa-router')
const session = require('koa-session2')
const Redis = require('ioredis')
const { JwtVerifier, StorageRedis, koaOauthMiddleware } = require('authone-jwt-verifier-node')
// oauth endpoints middleware creation
// You must set your own values here
const verifierOptions = {
issuer: 'https://auth1.protocol.one',
clientId: '5c6fc4888db4bc0001beacec',
clientSecret: 'RUOuk4bkWFNljuZzqwq5zrs0GdCLY9U3MJqubuDViUv7XQzgiU84y288Jh0klK1Z',
redirectUrl: 'https://myapp.protocol.one',
scopes: ['oauth', 'offline']
}
const postMessageHtmlTemplate = '<script>var result = { error: "{errorCode}", ' +
'access_token: "{accessToken}", ' +
'expires_in: {expiresIn}, success: {isSuccess} }; ' +
'var targetOrigin = "{targetOrigin}"</script>'
const endpointsOptions = {
namespace: 'auth1',
postMessageHtmlTemplate: postMessageHtmlTemplate,
postMessageTargetOrigin: '*'
}
const redisInstance = new Redis('localhost', 3369)
const redisStorage = new StorageRedis(redisInstance)
const jwtVerifier = new JwtVerifier(verifierOptions, redisStorage)
const oauthEndpoints = koaOauthMiddleware.oauthEndpoints(jwtVerifier, endpointsOptions)
// Oauth routes setup
const router = new Router()
router
.get('/login', oauthEndpoints.login)
.get('/callback', oauthEndpoints.authorize)
.get('/refresh', oauthEndpoints.refresh)
.get('/logout', oauthEndpoints.logout)
// CORS setup
const corsRoutes = ['/refresh', '/logout']
const corsValidOrigins = ['*']
const corsMiddleware = cors({
origin: function (ctx) {
if (!corsRoutes.includes(ctx.url)) {
return false
}
if (corsValidOrigins.includes('*')) {
return '*'
}
const requestOrigin = ctx.accept.headers.origin
if (!corsValidOrigins.includes(requestOrigin)) {
return ctx.throw(`${requestOrigin} is not a valid origin`)
}
return requestOrigin
},
allowMethods: ['GET', 'OPTIONS'],
maxAge: 5,
credentials: true,
allowHeaders: ['Content-Type', 'Authorization', 'Accept']
})
// App create and middleware setup
const app = new Koa()
app.keys = ['sessionCookieSignKey']
app.use(session({
signed: true,
httpOnly: true
}))
app.use(corsMiddleware)
app.use(router.routes())
app.use(router.allowedMethods())
const serverPort = 3000
// create server
const server = app.listen(serverPort, () => {
console.log(`Server listening on port: ${serverPort}`)
})
module.exports = server