forked from davetownsend/serverless-okta-lambda-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exampleAuth.js
71 lines (63 loc) · 2.08 KB
/
exampleAuth.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
const OktaJwtVerifier = require("@okta/jwt-verifier");
const AuthPolicy = require("./authPolicy");
const middy = require("middy");
const { ssm } = require("middy/middlewares");
const { STAGE: stage } = process.env;
let oktaJwtVerifier = {};
const setOktaVerificationParams = context => {
// check for empty verifier obj to allow for default cliet side caching
if (Object.keys(oktaJwtVerifier).length == 0) {
const { ISSUER: issuer, CLIENT_ID: clientId } = context;
oktaJwtVerifier = new OktaJwtVerifier({
issuer: issuer,
clientId: clientId
// assertClaims: {
// "scp.includes": ["your custom claims"]
// }
});
};
const verify = (event, context, cb) => {
setOktaVerificationParams(context);
const { AUDIENCE: audience } = context;
let arr = event.authorizationToken.split(" ");
let accessToken = arr[1];
let expectedAud = audience;
oktaJwtVerifier
.verifyAccessToken(accessToken, expectedAud)
.then(jwt => {
console.log(jwt.claims);
let claims = jwt.claims;
let apiOptions = {};
const arnParts = event.methodArn.split(":");
const apiGatewayArnPart = arnParts[5].split("/");
const awsAccountId = arnParts[4];
apiOptions.region = arnParts[3];
apiOptions.restApiId = apiGatewayArnPart[0];
apiOptions.stage = apiGatewayArnPart[1];
const method = apiGatewayArnPart[2];
let resource = "/";
if (apiGatewayArnPart[3]) {
resource += apiGatewayArnPart[3];
}
let policy = new AuthPolicy(claims.sub, awsAccountId, apiOptions);
policy.allowMethod(AuthPolicy.HttpVerb.GET, "/example/read");
console.log(JSON.stringify(policy.build()));
return cb(null, policy.build());
})
.catch(err => {
console.log(err);
return cb("Unauthorized");
});
};
module.exports.verify = middy(verify).use(
ssm({
cache: true,
cacheExpiryInMillis: 5 * 60 * 1000,
setToContext: true,
names: {
ISSUER: `/example/${stage}/okta/issuer`,
CLIENT_ID: `/example/${stage}/okta/clientid`,
AUDIENCE: `/example/${stage}/okta/audience`
}
})
);