Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adding jwks support #1

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion dotenv/cf-authentication-by-oauth2/.env-example
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ AUTHORIZE_REDIRECTURI_SHOULD_MATCH=true

CALLBACK_PATH="/callback"

JWT_ARGORITHM="RS256"
JWT_ALGORITHM="RS256"
JWT_TOKEN_PATH="/oauth/token"

DEBUG_ENABLE=false
13 changes: 13 additions & 0 deletions dotenv/cf-authentication-by-oauth2/.env-example-aad
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
CLIENT_DOMAIN="login.microsoftonline.com"
CLIENT_ID="{YOUR_AZURE_APPLICATION_ID}"
CLIENT_SECRET="{YOUR_AZURE_APPLICATION_CLIENT_SECRET}"

AUTHORIZE_URL ="https://login.microsoftonline.com/{YOUR_AZURE_TENANT_ID}/oauth2/v2.0/authorize"
AUTHORIZE_PARAMS="?response_type=code&scope=openid"
AUTHORIZE_REDIRECTURI_SHOULD_MATCH=true

CALLBACK_PATH="/callback"

JWT_ALGORITHM="RS256"
JWT_TOKEN_PATH="/{YOUR_AZURE_TENANT_ID}/oauth2/v2.0/token"
JWKS_URI="https://login.microsoftonline.com/{YOUR_AZURE_TENANT_ID}/discovery/v2.0/keys"
67 changes: 44 additions & 23 deletions lambda-assets/extensions/cf-authentication-by-oauth2/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const querystring = require("querystring");
const https = require("https");
const jsonwebtoken = require("jsonwebtoken");
const escape = require("lodash.escape");
const jwksClient = require('jwks-rsa');

const PUBLIC_PATHS = [/\/favicons\//];

Expand Down Expand Up @@ -82,19 +83,34 @@ function parseCookies(headers) {
return parsedCookie;
}

function validateToken(config, token) {
if (config.DEBUG_ENABLE) console.log("validateToken: enter, token = " + token + ", config.JWT_ARGORITHM = " + config.JWT_ARGORITHM);
async function getKey(config, kid) {
if (config.DEBUG_ENABLE) console.log("getKey: enter, kid = " + kid + ", config.JWKS_URI = " + config.JWKS_URI + ", config.CLIENT_PUBLIC_KEY = " + config.CLIENT_PUBLIC_KEY);
if (config.JWKS_URI !== null) {
const jwks_client = jwksClient({
jwksUri: config.JWKS_URI
});
const key = await jwks_client.getSigningKey(kid);
const public_key = key.getPublicKey();
if (config.DEBUG_ENABLE) {
console.log("getKey: public_key = (next line)")
console.log(public_key)
}
return public_key
};
return config.CLIENT_PUBLIC_KEY
}

function validateToken(config, token) {
if (config.DEBUG_ENABLE) console.log("validateToken: enter, token = " + token + ", config.JWT_ALGORITHM = " + config.JWT_ALGORITHM);
const decodedjwt = jsonwebtoken.decode(token, { complete: true });
if (config.DEBUG_ENABLE) {
const decodedjwt = jsonwebtoken.decode(token, {complete: true});
console.log("validateToken: token header = (next line)");
console.log(decodedjwt.header);
}
try {
const decoded = jsonwebtoken.verify(token, config.CLIENT_PUBLIC_KEY, {
algorithms: [config.JWT_ARGORITHM],
});

getKey(config, decodedjwt.header.kid).then(key => jsonwebtoken.verify(token, key, {
algorithms: [config.JWT_ALGORITHM],
}));
if (config.DEBUG_ENABLE) console.log("validateToken: return true");
return true;
} catch (err) {
Expand Down Expand Up @@ -253,44 +269,49 @@ function allowPublicPaths(config, request, callback) {
if (config.DEBUG_ENABLE) console.log("allowPublicPaths: callback request and return true.");
callback(null, request);
return true;
}else{
} else {
if (config.DEBUG_ENABLE) console.log("allowPublicPaths: return false.");
return false;
}
}

function getBoolean(value){
switch(value){
case true:
case "true":
case 1:
case "1":
case "on":
case "yes":
return true;
default:
return false;
}
function getBoolean(value) {
switch (value) {
case true:
case "true":
case 1:
case "1":
case "on":
case "yes":
return true;
default:
return false;
}
}

export function handler(event: any, context: any, callback: any) {
const config = {
CLIENT_DOMAIN: process.env.CLIENT_DOMAIN,
CLIENT_ID: process.env.CLIENT_ID,
CLIENT_SECRET: process.env.CLIENT_SECRET,
CLIENT_PUBLIC_KEY: Buffer.from(process.env.CLIENT_PUBLIC_KEY, 'base64').toString(),

AUTHORIZE_URL: process.env.AUTHORIZE_URL,
AUTHORIZE_PARAMS: Buffer.from(process.env.AUTHORIZE_PARAMS, 'base64').toString(),
AUTHORIZE_REDIRECTURI_SHOULD_MATCH: getBoolean(process.env.AUTHORIZE_REDIRECTURI_SHOULD_MATCH),

CALLBACK_PATH: process.env.CALLBACK_PATH,

JWT_ARGORITHM: process.env.JWT_ARGORITHM,
JWT_ALGORITHM: process.env.JWT_ALGORITHM,
JWT_TOKEN_PATH: process.env.JWT_TOKEN_PATH,

DEBUG_ENABLE: getBoolean(process.env.DEBUG_ENABLE),
};
if (process.env.JWKS_URI) {
config.JWKS_URI = process.env.JWKS_URI
}
else {
config.CLIENT_PUBLIC_KEY = Buffer.from(process.env.CLIENT_PUBLIC_KEY, 'base64').toString()
}

const request = event.Records[0].cf.request;

Expand All @@ -308,4 +329,4 @@ export function handler(event: any, context: any, callback: any) {
if (config.DEBUG_ENABLE) console.log("hanlder: callback request.");
callback(null, request);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@
"https": "^1.0.0",
"jsonwebtoken": "^8.5.1",
"lodash.escape": "^4.0.1",
"querystring": "^0.2.1"
"querystring": "^0.2.1",
"jwks-rsa": "^2.0.5"
},
"bundledDependencies": [
"querystring",
"https",
"jsonwebtoken",
"lodash.escape"
"lodash.escape",
"jwks-rsa"
]
}
}
148 changes: 148 additions & 0 deletions lambda-assets/extensions/cf-authentication-by-oauth2/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,100 @@
# yarn lockfile v1


"@panva/asn1.js@^1.0.0":
version "1.0.0"
resolved "https://registry.yarnpkg.com/@panva/asn1.js/-/asn1.js-1.0.0.tgz#dd55ae7b8129e02049f009408b97c61ccf9032f6"
integrity sha512-UdkG3mLEqXgnlKsWanWcgb6dOjUzJ+XC5f+aWw30qrtjxeNUSfKX1cd5FBzOaXQumoe9nIqeZUvrRJS03HCCtw==

"@types/body-parser@*":
version "1.19.1"
resolved "https://registry.yarnpkg.com/@types/body-parser/-/body-parser-1.19.1.tgz#0c0174c42a7d017b818303d4b5d969cb0b75929c"
integrity sha512-a6bTJ21vFOGIkwM0kzh9Yr89ziVxq4vYH2fQ6N8AeipEzai/cFK6aGMArIkUeIdRIgpwQa+2bXiLuUJCpSf2Cg==
dependencies:
"@types/connect" "*"
"@types/node" "*"

"@types/connect@*":
version "3.4.35"
resolved "https://registry.yarnpkg.com/@types/connect/-/connect-3.4.35.tgz#5fcf6ae445e4021d1fc2219a4873cc73a3bb2ad1"
integrity sha512-cdeYyv4KWoEgpBISTxWvqYsVy444DOqehiF3fM3ne10AmJ62RSyNkUnxMJXHQWRQQX2eR94m5y1IZyDwBjV9FQ==
dependencies:
"@types/node" "*"

"@types/express-jwt@0.0.42":
version "0.0.42"
resolved "https://registry.yarnpkg.com/@types/express-jwt/-/express-jwt-0.0.42.tgz#4f04e1fadf9d18725950dc041808a4a4adf7f5ae"
integrity sha512-WszgUddvM1t5dPpJ3LhWNH8kfNN8GPIBrAGxgIYXVCEGx6Bx4A036aAuf/r5WH9DIEdlmp7gHOYvSM6U87B0ag==
dependencies:
"@types/express" "*"
"@types/express-unless" "*"

"@types/express-serve-static-core@^4.17.18":
version "4.17.24"
resolved "https://registry.yarnpkg.com/@types/express-serve-static-core/-/express-serve-static-core-4.17.24.tgz#ea41f93bf7e0d59cd5a76665068ed6aab6815c07"
integrity sha512-3UJuW+Qxhzwjq3xhwXm2onQcFHn76frIYVbTu+kn24LFxI+dEhdfISDFovPB8VpEgW8oQCTpRuCe+0zJxB7NEA==
dependencies:
"@types/node" "*"
"@types/qs" "*"
"@types/range-parser" "*"

"@types/express-unless@*":
version "0.5.2"
resolved "https://registry.yarnpkg.com/@types/express-unless/-/express-unless-0.5.2.tgz#07e29883d280778588644b03563d8796f870f20e"
integrity sha512-Q74UyYRX/zIgl1HSp9tUX2PlG8glkVm+59r7aK4KGKzC5jqKIOX6rrVLRQrzpZUQ84VukHtRoeAuon2nIssHPQ==
dependencies:
"@types/express" "*"

"@types/express@*":
version "4.17.13"
resolved "https://registry.yarnpkg.com/@types/express/-/express-4.17.13.tgz#a76e2995728999bab51a33fabce1d705a3709034"
integrity sha512-6bSZTPaTIACxn48l50SR+axgrqm6qXFIxrdAKaG6PaJk3+zuUr35hBlgT7vOmJcum+OEaIBLtHV/qloEAFITeA==
dependencies:
"@types/body-parser" "*"
"@types/express-serve-static-core" "^4.17.18"
"@types/qs" "*"
"@types/serve-static" "*"

"@types/mime@^1":
version "1.3.2"
resolved "https://registry.yarnpkg.com/@types/mime/-/mime-1.3.2.tgz#93e25bf9ee75fe0fd80b594bc4feb0e862111b5a"
integrity sha512-YATxVxgRqNH6nHEIsvg6k2Boc1JHI9ZbH5iWFFv/MTkchz3b1ieGDa5T0a9RznNdI0KhVbdbWSN+KWWrQZRxTw==

"@types/node@*":
version "16.11.3"
resolved "https://registry.yarnpkg.com/@types/node/-/node-16.11.3.tgz#fad0b069ec205b0e81429c805d306d2c12e26be1"
integrity sha512-aIYL9Eemcecs1y77XzFGiSc+FdfN58k4J23UEe6+hynf4Wd9g4DzQPwIKL080vSMuubFqy2hWwOzCtJdc6vFKw==

"@types/qs@*":
version "6.9.7"
resolved "https://registry.yarnpkg.com/@types/qs/-/qs-6.9.7.tgz#63bb7d067db107cc1e457c303bc25d511febf6cb"
integrity sha512-FGa1F62FT09qcrueBA6qYTrJPVDzah9a+493+o2PCXsesWHIn27G98TsSMs3WPNbZIEj4+VJf6saSFpvD+3Zsw==

"@types/range-parser@*":
version "1.2.4"
resolved "https://registry.yarnpkg.com/@types/range-parser/-/range-parser-1.2.4.tgz#cd667bcfdd025213aafb7ca5915a932590acdcdc"
integrity sha512-EEhsLsD6UsDM1yFhAvy0Cjr6VwmpMWqFBCb9w07wVugF7w9nfajxLuVmngTIpgS6svCnm6Vaw+MZhoDCKnOfsw==

"@types/serve-static@*":
version "1.13.10"
resolved "https://registry.yarnpkg.com/@types/serve-static/-/serve-static-1.13.10.tgz#f5e0ce8797d2d7cc5ebeda48a52c96c4fa47a8d9"
integrity sha512-nCkHGI4w7ZgAdNkrEu0bv+4xNV/XDqW+DydknebMOQwkpDGx8G+HTlj7R7ABI8i8nKxVw0wtKPi1D+lPOkh4YQ==
dependencies:
"@types/mime" "^1"
"@types/node" "*"

buffer-equal-constant-time@1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz#f8e71132f7ffe6e01a5c9697a4c6f3e48d5cc819"
integrity sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=

debug@^4.3.2:
version "4.3.2"
resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.2.tgz#f0a49c18ac8779e31d4a0c6029dfb76873c7428b"
integrity sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==
dependencies:
ms "2.1.2"

ecdsa-sig-formatter@1.0.11:
version "1.0.11"
resolved "https://registry.yarnpkg.com/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz#ae0f0fa2d85045ef14a817daa3ce9acd0489e5bf"
Expand All @@ -19,6 +108,13 @@ https@^1.0.0:
resolved "https://registry.yarnpkg.com/https/-/https-1.0.0.tgz#3c37c7ae1a8eeb966904a2ad1e975a194b7ed3a4"
integrity sha1-PDfHrhqO65ZpBKKtHpdaGUt+06Q=

jose@^2.0.5:
version "2.0.5"
resolved "https://registry.yarnpkg.com/jose/-/jose-2.0.5.tgz#29746a18d9fff7dcf9d5d2a6f62cb0c7cd27abd3"
integrity sha512-BAiDNeDKTMgk4tvD0BbxJ8xHEHBZgpeRZ1zGPPsitSyMgjoMWiLGYAE7H7NpP5h0lPppQajQs871E8NHUrzVPA==
dependencies:
"@panva/asn1.js" "^1.0.0"

jsonwebtoken@^8.5.1:
version "8.5.1"
resolved "https://registry.yarnpkg.com/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz#00e71e0b8df54c2121a1f26137df2280673bcc0d"
Expand All @@ -44,6 +140,17 @@ jwa@^1.4.1:
ecdsa-sig-formatter "1.0.11"
safe-buffer "^5.0.1"

jwks-rsa@^2.0.5:
version "2.0.5"
resolved "https://registry.yarnpkg.com/jwks-rsa/-/jwks-rsa-2.0.5.tgz#5dc911cdade803a149b7d4d41404a7c1bf2c221a"
integrity sha512-fliHfsiBRzEU0nXzSvwnh0hynzGB0WihF+CinKbSRlaqRxbqqKf2xbBPgwc8mzf18/WgwlG8e5eTpfSTBcU4DQ==
dependencies:
"@types/express-jwt" "0.0.42"
debug "^4.3.2"
jose "^2.0.5"
limiter "^1.1.5"
lru-memoizer "^2.1.4"

jws@^3.2.2:
version "3.2.2"
resolved "https://registry.yarnpkg.com/jws/-/jws-3.2.2.tgz#001099f3639468c9414000e99995fa52fb478304"
Expand All @@ -52,6 +159,16 @@ jws@^3.2.2:
jwa "^1.4.1"
safe-buffer "^5.0.1"

limiter@^1.1.5:
version "1.1.5"
resolved "https://registry.yarnpkg.com/limiter/-/limiter-1.1.5.tgz#8f92a25b3b16c6131293a0cc834b4a838a2aa7c2"
integrity sha512-FWWMIEOxz3GwUI4Ts/IvgVy6LPvoMPgjMdQ185nN6psJyBJ4yOpzqm695/h5umdLJg2vW3GR5iG11MAkR2AzJA==

lodash.clonedeep@^4.5.0:
version "4.5.0"
resolved "https://registry.yarnpkg.com/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz#e23f3f9c4f8fbdde872529c1071857a086e5ccef"
integrity sha1-4j8/nE+Pvd6HJSnBBxhXoIblzO8=

lodash.escape@^4.0.1:
version "4.0.1"
resolved "https://registry.yarnpkg.com/lodash.escape/-/lodash.escape-4.0.1.tgz#c9044690c21e04294beaa517712fded1fa88de98"
Expand Down Expand Up @@ -92,11 +209,37 @@ lodash.once@^4.0.0:
resolved "https://registry.yarnpkg.com/lodash.once/-/lodash.once-4.1.1.tgz#0dd3971213c7c56df880977d504c88fb471a97ac"
integrity sha1-DdOXEhPHxW34gJd9UEyI+0cal6w=

lru-cache@~4.0.0:
version "4.0.2"
resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-4.0.2.tgz#1d17679c069cda5d040991a09dbc2c0db377e55e"
integrity sha1-HRdnnAac2l0ECZGgnbwsDbN35V4=
dependencies:
pseudomap "^1.0.1"
yallist "^2.0.0"

lru-memoizer@^2.1.4:
version "2.1.4"
resolved "https://registry.yarnpkg.com/lru-memoizer/-/lru-memoizer-2.1.4.tgz#b864d92b557f00b1eeb322156a0409cb06dafac6"
integrity sha512-IXAq50s4qwrOBrXJklY+KhgZF+5y98PDaNo0gi/v2KQBFLyWr+JyFvijZXkGKjQj/h9c0OwoE+JZbwUXce76hQ==
dependencies:
lodash.clonedeep "^4.5.0"
lru-cache "~4.0.0"

ms@2.1.2:
version "2.1.2"
resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009"
integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==

ms@^2.1.1:
version "2.1.3"
resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2"
integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==

pseudomap@^1.0.1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/pseudomap/-/pseudomap-1.0.2.tgz#f052a28da70e618917ef0a8ac34c1ae5a68286b3"
integrity sha1-8FKijacOYYkX7wqKw0wa5aaChrM=

querystring@^0.2.1:
version "0.2.1"
resolved "https://registry.yarnpkg.com/querystring/-/querystring-0.2.1.tgz#40d77615bb09d16902a85c3e38aa8b5ed761c2dd"
Expand All @@ -111,3 +254,8 @@ semver@^5.6.0:
version "5.7.1"
resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7"
integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==

yallist@^2.0.0:
version "2.1.2"
resolved "https://registry.yarnpkg.com/yallist/-/yallist-2.1.2.tgz#1c11f9218f076089a47dd512f93c6699a6a81d52"
integrity sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=
16 changes: 15 additions & 1 deletion src/demo/cf-authentication-by-oauth2/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,29 @@ Usually you will setup one application or client at your identity provider (IdP)
- Allowed Web Origins: **https://abcabcabcabcab.cloudfront.net**
- Get your public key at Advanced Settings --> Certificates tab --> Signing Certificate.

### Example: AzureAD

- [Register an application](https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app#register-an-application)
- [Add a redirect URI](https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app#register-an-application).
- Add a `Web` platform.
- Add the `redirect URI`. This value will need to match the extension's callback URI.
- [Add a client secret](https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app#add-a-client-secret)

### Example: KeyCloak

Detailed KeyCloak configuration screenshots describes in this blog post:

- (en) [Using AWS CDK to Deploy Static Website ft. OAuth 2.0 Authorization Code](https://www.ernestchiang.com/en/posts/2021/implementing-cloudfront-lambda-at-edge-oauth2-by-cdk/)
- (zh) [使用 AWS CDK 快速部署靜態網站,搭配 CloudFront Lambda@Edge 擴充 OAuth 2.0 Authorization Code 授權流程](https://www.ernestchiang.com/zh/posts/2021/implementing-cloudfront-lambda-at-edge-oauth2-by-cdk/)

## Step 2: duplicate & edit .env

Please make a copy from `dotenv/cf-authentication-by-oauth2/.env-example` to `dotenv/cf-authentication-by-oauth2/.env`, then edit `.env`. Place all the parameters and information from your identity provider (IdP).
Copy one of the example files listed below to `dotenv/cf-authentication-by-oauth2/.env`, then edit `.env`. Place all the parameters and information from your identity provider (IdP).

### Examples
- [.env-example](https://github.com/pahud/cdk-cloudfront-plus/blob/main/dotenv/cf-authentication-by-oauth2/.env-example) - Useful for implementations using a single, static, JWK
- [.env-example-aad](https://github.com/pahud/cdk-cloudfront-plus/blob/main/dotenv/cf-authentication-by-oauth2/.env-example-aad) - AzureAD example. Also shows the `JWKS_URI` in action, for identity providers that support it.


```sh
cp dotenv/cf-authentication-by-oauth2/.env-example dotenv/cf-authentication-by-oauth2/.env
Expand Down
Loading