feat(auth): implement OIDC JWT verification with dynamic identity provider support

- Added JwtService (azure-jwt.service.ts) to verify tokens from multiple IdPs (Microsoft Entra ID, Amazon Cognito)
- Implemented dynamic provider configuration (issuer, audience, jwksUri)
- Added JwtAuthGuard for NestJS to handle JWT validation via jose library
- Integrated @Public() and @IdP() decorators for route-level control
- Audience () and issuer () validation logic aligned with OIDC standards
- Added clock tolerance and allowed algorithm checks for security hardening
This commit is contained in:
dahyeon committed 2025-11-08 03:33:36 +00:00
1 parent 02255d7240
commit d6b9477094
14 files changed
+346 -47

No files matched your search

+11 -1
View File
@@ -3,6 +3,16 @@
"collection": "@nestjs/schematics", "collection": "@nestjs/schematics",
"sourceRoot": "src", "sourceRoot": "src",
"compilerOptions": { "compilerOptions": {
"deleteOutDir": true "deleteOutDir": true,
"plugins": [
{
"name": "@nestjs/swagger",
"options": {
"classValidatorShim": false,
"introspectComments": true,
"skipAutoHttpCode": true
}
}
]
} }
} }
+20 -24
View File
@@ -15,6 +15,7 @@
"@nestjs/core": "^11.0.1", "@nestjs/core": "^11.0.1",
"@nestjs/platform-express": "^11.0.1", "@nestjs/platform-express": "^11.0.1",
"@nestjs/swagger": "^11.2.1", "@nestjs/swagger": "^11.2.1",
"jose": "^6.1.0",
"mongoose": "^8.19.3", "mongoose": "^8.19.3",
"nats": "^2.29.3", "nats": "^2.29.3",
"reflect-metadata": "^0.2.2", "reflect-metadata": "^0.2.2",
@@ -502,7 +503,6 @@
"resolved": "https://registry.npmjs.org/@aws-sdk/client-sts/-/client-sts-3.600.0.tgz", "resolved": "https://registry.npmjs.org/@aws-sdk/client-sts/-/client-sts-3.600.0.tgz",
"integrity": "sha512-KQG97B7LvTtTiGmjlrG1LRAY8wUvCQzrmZVV5bjrJ/1oXAU7DITYwVbSJeX9NWg6hDuSk0VE3MFwIXS2SvfLIA==", "integrity": "sha512-KQG97B7LvTtTiGmjlrG1LRAY8wUvCQzrmZVV5bjrJ/1oXAU7DITYwVbSJeX9NWg6hDuSk0VE3MFwIXS2SvfLIA==",
"license": "Apache-2.0", "license": "Apache-2.0",
"peer": true,
"dependencies": { "dependencies": {
"@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-browser": "5.2.0",
"@aws-crypto/sha256-js": "5.2.0", "@aws-crypto/sha256-js": "5.2.0",
@@ -1421,7 +1421,6 @@
"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==", "integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@babel/code-frame": "^7.27.1", "@babel/code-frame": "^7.27.1",
"@babel/generator": "^7.28.5", "@babel/generator": "^7.28.5",
@@ -3353,7 +3352,6 @@
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"fast-deep-equal": "^3.1.3", "fast-deep-equal": "^3.1.3",
"fast-uri": "^3.0.1", "fast-uri": "^3.0.1",
@@ -3538,7 +3536,6 @@
"resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.1.8.tgz", "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.1.8.tgz",
"integrity": "sha512-bbsOqwld/GdBfiRNc4nnjyWWENDEicq4SH+R5AuYatvf++vf1x5JIsHB1i1KtfZMD3eRte0D4K9WXuAYil6XAg==", "integrity": "sha512-bbsOqwld/GdBfiRNc4nnjyWWENDEicq4SH+R5AuYatvf++vf1x5JIsHB1i1KtfZMD3eRte0D4K9WXuAYil6XAg==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"file-type": "21.0.0", "file-type": "21.0.0",
"iterare": "1.2.1", "iterare": "1.2.1",
@@ -3586,7 +3583,6 @@
"integrity": "sha512-7riWfmTmMhCJHZ5ZiaG+crj4t85IPCq/wLRuOUSigBYyFT2JZj0lVHtAdf4Davp9ouNI8GINBDt9h9b5Gz9nTw==", "integrity": "sha512-7riWfmTmMhCJHZ5ZiaG+crj4t85IPCq/wLRuOUSigBYyFT2JZj0lVHtAdf4Davp9ouNI8GINBDt9h9b5Gz9nTw==",
"hasInstallScript": true, "hasInstallScript": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@nuxt/opencollective": "0.4.1", "@nuxt/opencollective": "0.4.1",
"fast-safe-stringify": "2.1.1", "fast-safe-stringify": "2.1.1",
@@ -3647,7 +3643,6 @@
"resolved": "https://registry.npmjs.org/@nestjs/platform-express/-/platform-express-11.1.8.tgz", "resolved": "https://registry.npmjs.org/@nestjs/platform-express/-/platform-express-11.1.8.tgz",
"integrity": "sha512-rL6pZH9BW7BnL5X2eWbJMtt86uloAKjFgyY5+L2UkizgfEp7rgAs0+Z1z0BcW2Pgu5+q8O7RKPNyHJ/9ZNz/ZQ==", "integrity": "sha512-rL6pZH9BW7BnL5X2eWbJMtt86uloAKjFgyY5+L2UkizgfEp7rgAs0+Z1z0BcW2Pgu5+q8O7RKPNyHJ/9ZNz/ZQ==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"cors": "2.8.5", "cors": "2.8.5",
"express": "5.1.0", "express": "5.1.0",
@@ -4755,7 +4750,6 @@
"integrity": "sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag==", "integrity": "sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@types/estree": "*", "@types/estree": "*",
"@types/json-schema": "*" "@types/json-schema": "*"
@@ -4876,7 +4870,6 @@
"integrity": "sha512-xpr/lmLPQEj+TUnHmR+Ab91/glhJvsqcjB+yY0Ix9GO70H6Lb4FHH5GeqdOE5btAx7eIMwuHkp4H2MSkLcqWbA==", "integrity": "sha512-xpr/lmLPQEj+TUnHmR+Ab91/glhJvsqcjB+yY0Ix9GO70H6Lb4FHH5GeqdOE5btAx7eIMwuHkp4H2MSkLcqWbA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"undici-types": "~6.21.0" "undici-types": "~6.21.0"
} }
@@ -5037,7 +5030,6 @@
"integrity": "sha512-6m1I5RmHBGTnUGS113G04DMu3CpSdxCAU/UvtjNWL4Nuf3MW9tQhiJqRlHzChIkhy6kZSAQmc+I1bcGjE3yNKg==", "integrity": "sha512-6m1I5RmHBGTnUGS113G04DMu3CpSdxCAU/UvtjNWL4Nuf3MW9tQhiJqRlHzChIkhy6kZSAQmc+I1bcGjE3yNKg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@typescript-eslint/scope-manager": "8.46.3", "@typescript-eslint/scope-manager": "8.46.3",
"@typescript-eslint/types": "8.46.3", "@typescript-eslint/types": "8.46.3",
@@ -5720,7 +5712,6 @@
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"bin": { "bin": {
"acorn": "bin/acorn" "acorn": "bin/acorn"
}, },
@@ -5770,7 +5761,6 @@
"integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"fast-deep-equal": "^3.1.1", "fast-deep-equal": "^3.1.1",
"fast-json-stable-stringify": "^2.0.0", "fast-json-stable-stringify": "^2.0.0",
@@ -6207,7 +6197,6 @@
} }
], ],
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"baseline-browser-mapping": "^2.8.19", "baseline-browser-mapping": "^2.8.19",
"caniuse-lite": "^1.0.30001751", "caniuse-lite": "^1.0.30001751",
@@ -6415,7 +6404,6 @@
"integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"readdirp": "^4.0.1" "readdirp": "^4.0.1"
}, },
@@ -7127,7 +7115,6 @@
"integrity": "sha512-BhHmn2yNOFA9H9JmmIVKJmd288g9hrVRDkdoIgRCRuSySRUHH7r/DI6aAXW9T1WwUuY3DFgrcaqB+deURBLR5g==", "integrity": "sha512-BhHmn2yNOFA9H9JmmIVKJmd288g9hrVRDkdoIgRCRuSySRUHH7r/DI6aAXW9T1WwUuY3DFgrcaqB+deURBLR5g==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/eslint-utils": "^4.8.0",
"@eslint-community/regexpp": "^4.12.1", "@eslint-community/regexpp": "^4.12.1",
@@ -7188,7 +7175,6 @@
"integrity": "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==", "integrity": "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"bin": { "bin": {
"eslint-config-prettier": "bin/cli.js" "eslint-config-prettier": "bin/cli.js"
}, },
@@ -8510,7 +8496,6 @@
"integrity": "sha512-F26gjC0yWN8uAA5m5Ss8ZQf5nDHWGlN/xWZIh8S5SRbsEKBovwZhxGd6LJlbZYxBgCYOtreSUyb8hpXyGC5O4A==", "integrity": "sha512-F26gjC0yWN8uAA5m5Ss8ZQf5nDHWGlN/xWZIh8S5SRbsEKBovwZhxGd6LJlbZYxBgCYOtreSUyb8hpXyGC5O4A==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@jest/core": "30.2.0", "@jest/core": "30.2.0",
"@jest/types": "30.2.0", "@jest/types": "30.2.0",
@@ -9280,6 +9265,15 @@
"url": "https://github.com/chalk/supports-color?sponsor=1" "url": "https://github.com/chalk/supports-color?sponsor=1"
} }
}, },
"node_modules/jose": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/jose/-/jose-6.1.0.tgz",
"integrity": "sha512-TTQJyoEoKcC1lscpVDCSsVgYzUDg/0Bt3WE//WiTPK6uOCQC2KZS4MpugbMWt/zyjkopgZoXhZuCi00gLudfUA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
},
"node_modules/js-tokens": { "node_modules/js-tokens": {
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
@@ -10461,7 +10455,6 @@
"integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==", "integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"bin": { "bin": {
"prettier": "bin/prettier.cjs" "prettier": "bin/prettier.cjs"
}, },
@@ -10667,8 +10660,7 @@
"version": "0.2.2", "version": "0.2.2",
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz",
"integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==",
"license": "Apache-2.0", "license": "Apache-2.0"
"peer": true
}, },
"node_modules/require-directory": { "node_modules/require-directory": {
"version": "2.1.1", "version": "2.1.1",
@@ -10800,7 +10792,6 @@
"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz",
"integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==",
"license": "Apache-2.0", "license": "Apache-2.0",
"peer": true,
"dependencies": { "dependencies": {
"tslib": "^2.1.0" "tslib": "^2.1.0"
} }
@@ -11508,7 +11499,6 @@
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"fast-deep-equal": "^3.1.3", "fast-deep-equal": "^3.1.3",
"fast-uri": "^3.0.1", "fast-uri": "^3.0.1",
@@ -11828,7 +11818,6 @@
"integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@cspotcode/source-map-support": "^0.8.0", "@cspotcode/source-map-support": "^0.8.0",
"@tsconfig/node10": "^1.0.7", "@tsconfig/node10": "^1.0.7",
@@ -11981,7 +11970,6 @@
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"license": "Apache-2.0", "license": "Apache-2.0",
"peer": true,
"bin": { "bin": {
"tsc": "bin/tsc", "tsc": "bin/tsc",
"tsserver": "bin/tsserver" "tsserver": "bin/tsserver"
@@ -12341,6 +12329,7 @@
"integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==", "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"ajv": "^8.0.0" "ajv": "^8.0.0"
}, },
@@ -12359,6 +12348,7 @@
"integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==", "integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"fast-deep-equal": "^3.1.3" "fast-deep-equal": "^3.1.3"
}, },
@@ -12372,6 +12362,7 @@
"integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==",
"dev": true, "dev": true,
"license": "BSD-2-Clause", "license": "BSD-2-Clause",
"peer": true,
"dependencies": { "dependencies": {
"esrecurse": "^4.3.0", "esrecurse": "^4.3.0",
"estraverse": "^4.1.1" "estraverse": "^4.1.1"
@@ -12386,6 +12377,7 @@
"integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==",
"dev": true, "dev": true,
"license": "BSD-2-Clause", "license": "BSD-2-Clause",
"peer": true,
"engines": { "engines": {
"node": ">=4.0" "node": ">=4.0"
} }
@@ -12395,7 +12387,8 @@
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
"dev": true, "dev": true,
"license": "MIT" "license": "MIT",
"peer": true
}, },
"node_modules/webpack/node_modules/mime-db": { "node_modules/webpack/node_modules/mime-db": {
"version": "1.52.0", "version": "1.52.0",
@@ -12403,6 +12396,7 @@
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">= 0.6" "node": ">= 0.6"
} }
@@ -12413,6 +12407,7 @@
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"mime-db": "1.52.0" "mime-db": "1.52.0"
}, },
@@ -12426,6 +12421,7 @@
"integrity": "sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA==", "integrity": "sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@types/json-schema": "^7.0.9", "@types/json-schema": "^7.0.9",
"ajv": "^8.9.0", "ajv": "^8.9.0",
+1
View File
@@ -26,6 +26,7 @@
"@nestjs/core": "^11.0.1", "@nestjs/core": "^11.0.1",
"@nestjs/platform-express": "^11.0.1", "@nestjs/platform-express": "^11.0.1",
"@nestjs/swagger": "^11.2.1", "@nestjs/swagger": "^11.2.1",
"jose": "^6.1.0",
"mongoose": "^8.19.3", "mongoose": "^8.19.3",
"nats": "^2.29.3", "nats": "^2.29.3",
"reflect-metadata": "^0.2.2", "reflect-metadata": "^0.2.2",
+7 -3
View File
@@ -1,12 +1,16 @@
import { Controller, Get } from '@nestjs/common'; import { Controller, Get, UseGuards } from '@nestjs/common';
import { AppService } from './app.service'; import { AppService } from './app.service';
import { JwtAuthGuard } from './modules/global/auth/jwt.guard';
import { AllowPublicAccess } from './modules/global/auth/allow-public-access.decorator';
@UseGuards(JwtAuthGuard)
@Controller() @Controller()
export class AppController { export class AppController {
constructor(private readonly appService: AppService) {} constructor(private readonly appService: AppService) {}
@AllowPublicAccess()
@Get() @Get()
getHello(): string { isHealthy(): string {
return this.appService.getHello(); return this.appService.isHealthy();
} }
} }
+3 -1
View File
@@ -3,6 +3,7 @@ import { AppController } from './app.controller';
import { AppService } from './app.service'; import { AppService } from './app.service';
import { GlobalModule } from './modules/global/global.module'; import { GlobalModule } from './modules/global/global.module';
import { ConfigModule } from '@nestjs/config'; import { ConfigModule } from '@nestjs/config';
import { AccountModule } from './modules/account/account.module';
@Module({ @Module({
imports: [ imports: [
@@ -10,7 +11,8 @@ import { ConfigModule } from '@nestjs/config';
isGlobal: true, isGlobal: true,
envFilePath: process.env.NODE_ENV === 'prod' ? '.env.prod' : process.env.NODE_ENV === 'test' ? '.env.test' : '.env.dev', envFilePath: process.env.NODE_ENV === 'prod' ? '.env.prod' : process.env.NODE_ENV === 'test' ? '.env.test' : '.env.dev',
}), }),
GlobalModule], GlobalModule,
AccountModule],
controllers: [AppController], controllers: [AppController],
providers: [AppService], providers: [AppService],
}) })
+5 -2
View File
@@ -2,7 +2,10 @@ import { Injectable } from '@nestjs/common';
@Injectable() @Injectable()
export class AppService { export class AppService {
getHello(): string { // getHello(): string {
return 'Hello World!'; // return 'Hello World!';
// }
isHealthy(): string {
return 'OK';
} }
} }
+17 -13
View File
@@ -5,20 +5,24 @@ import { AppModule } from './app.module';
async function bootstrap() { async function bootstrap() {
const app = await NestFactory.create(AppModule); const app = await NestFactory.create(AppModule);
const apiVersion = 1;
const config = new DocumentBuilder() if (process.env.NODE_ENV === 'dev' || process.env.NODE_ENV === 'test') {
.setTitle('Cats example') const config = new DocumentBuilder()
.setDescription('The cats API description') .setTitle('Gemwiki API')
.setVersion('1.0') .setDescription('The Gemwiki API description')
.addTag('cats') .setVersion('1.0')
.build(); .addTag('gemwiki')
const options: SwaggerCustomOptions = { .build();
ui: false, // Swagger UI is disabled const options: SwaggerCustomOptions = {
raw: ['yaml'], // JSON API definition is still accessible (YAML is disabled) ui: false,
} raw: ['yaml'],
const documentFactory = () => SwaggerModule.createDocument(app, config); }
SwaggerModule.setup('api', app, documentFactory, options); const documentFactory = () => SwaggerModule.createDocument(app, config);
SwaggerModule.setup(`v${apiVersion}/api`, app, documentFactory, options);
}
await app.listen(process.env.PORT ?? 3000); app.setGlobalPrefix(`v${apiVersion}`);
await app.listen(process.env.PORT ?? 3415);
} }
bootstrap(); bootstrap();
+20
View File
@@ -0,0 +1,20 @@
import { Controller, Get, UseGuards } from "@nestjs/common";
import { AccountService } from "./account.service";
import { JwtAuthGuard } from "../global/auth/jwt.guard";
@Controller('account')
export class AccountController {
constructor(private readonly accountService: AccountService) {}
@Get('signin')
signIn(): string {
return this.accountService.signIn();
}
@Get()
@UseGuards(JwtAuthGuard)
getAccountInfo(): string {
return this.accountService.getAccountInfo();
}
}
+9
View File
@@ -0,0 +1,9 @@
import { Module } from "@nestjs/common";
import { AccountController } from "./account.controller";
import { AccountService } from "./account.service";
@Module({
controllers: [AccountController],
providers: [AccountService],
})
export class AccountModule {}
+12
View File
@@ -0,0 +1,12 @@
import { Injectable } from "@nestjs/common";
@Injectable()
export class AccountService {
signIn(): string {
return 'Sign In Successful';
}
getAccountInfo(): string {
return 'Account Information';
}
}
@@ -0,0 +1,4 @@
// auth/public.decorator.ts
import { SetMetadata } from '@nestjs/common';
export const METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED = 'IS_PUBLIC_ACCESS_ALLOWED';
export const AllowPublicAccess = () => SetMetadata(METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, true);
+96
View File
@@ -0,0 +1,96 @@
// src/auth/jwt.guard.ts
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
ForbiddenException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { IdentityProviderName, JwtService } from './jwt.service';
import { decodeJwt } from 'jose';
import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from './allow-public-access.decorator';
@Injectable()
export class JwtAuthGuard implements CanActivate {
constructor(
private readonly reflector: Reflector,
private readonly jwtService: JwtService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const isPublicAccessAllowed = this.reflector.getAllAndOverride<boolean>(METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, [
context.getHandler(),
context.getClass(),
]);
if (isPublicAccessAllowed) return true;
const request = context.switchToHttp().getRequest();
const authz = request.headers?.authorization as string | undefined;
if (!authz || !authz.startsWith('Bearer ')) {
throw new UnauthorizedException('Missing or invalid Authorization header');
}
const token = authz.slice('Bearer '.length).trim();
if (!token) {
throw new UnauthorizedException('Empty bearer token');
}
// let identityProvider =
// this.reflector.getAllAndOverride<IdentityProviderName>(IDP_KEY, [
// context.getHandler(),
// context.getClass(),
// ]);
// if (!identityProvider) {
// }
let identityProvider: IdentityProviderName;
try {
const { iss } = decodeJwt(token) as { iss?: string };
if (!iss) {
throw new UnauthorizedException('Token has no issuer (iss) claim');
}
identityProvider = this.pickIdPFromIssuer(iss);
} catch (e) {
throw new UnauthorizedException(
e instanceof Error ? e.message : 'Unable to decode token',
);
}
try {
const verifyResult = await this.jwtService.verify(token, identityProvider);
request.user = verifyResult.payload;
request.tokenHeader = verifyResult.protectedHeader;
request.identityProvider = identityProvider;
return true;
} catch (e) {
const msg = e instanceof Error ? e.message : 'JWT verification failed';
// iss/aud 불일치는 보통 401, 접근권한 이슈는 403 (여기선 401로 통일)
throw new UnauthorizedException(msg);
}
}
/**
* issuer(iss)로부터 IdP 추정
* - Entra ID: https://login.microsoftonline.com/<tenant>/v2.0
* - Cognito: https://cognito-idp.<region>.amazonaws.com/<userPoolId>
*/
private pickIdPFromIssuer(issuer: string): IdentityProviderName {
const lower = issuer.toLowerCase();
if (lower.includes('login.microsoftonline.com')) {
return 'MICROSOFT_ENTRAID';
}
if (lower.includes('cognito-idp.') && lower.includes('.amazonaws.com')) {
return 'AMAZON_COGNITO';
}
// 필요하다면 여기서 jwtService 내부에 등록된 issuer들로 엄격 매칭하도록 변경 가능:
// const configuredIssuers = this.jwtService.getConfiguredIssuers?.();
// ...
throw new ForbiddenException(`Unknown issuer: ${issuer}`);
}
}
+137
View File
@@ -0,0 +1,137 @@
// src/auth/azure-jwt.service.ts
import { Injectable, OnModuleInit } from '@nestjs/common';
import { SecretService } from '../secret/secret.service';
import {
createRemoteJWKSet,
jwtVerify,
JWTPayload,
JWTVerifyResult,
} from 'jose';
/**
* Microsoft Entra ID 를 IdP로 사용하는 OpenID Connect 인증 관련 모듈.
* OIDC 인증 흐름 -> https://learn.microsoft.com/ko-kr/entra/architecture/auth-oidc 문서 참조.
* 추후 IdP 확장 고려해 IdP 별로 해당 IdP 이름을 접두사에 붙인다.
*/
export type IdentityProviderName = 'MICROSOFT_ENTRAID' | 'AMAZON_COGNITO';
// export type IdentityProvider = {
// [x in IdentityProviderName]: EntraIDIdentityProviderMetadata
// };
// export type EntraIDIdentityProviderMetadata = {
// issuer: string;
// authorizationEndpoint: string;
// tokenEndpoint: string;
// userInfoEndpoint: string;
// jwksUri: string;
// }
@Injectable()
export class JwtService implements OnModuleInit {
private jwtClaimAudience: string;
private MICROSOFT_ENTRAID_tenantId: string;
private MICROSOFT_ENTRAID_allowedAlgs: string;
private MICROSOFT_ENTRAID_issuer: string;
private MICROSOFT_ENTRAID_jwksUri: string;
private MICROSOFT_ENTRAID_jwks: ReturnType<typeof createRemoteJWKSet>;
private readonly tokenSigningAlgValuesSupported = ['RS256'];
private readonly clockTolerance =
Number(process.env.JWT_CLOCK_TOLERANCE || 5); // seconds
constructor(
private readonly secretService: SecretService
) {}
public async onModuleInit() {
await this.secretService.ready()
this.jwtClaimAudience = await this.secretService.get('JWT_CLAIM_AUDIENCE')
this.MICROSOFT_ENTRAID_tenantId = await this.secretService.get('MICROSOFT_ENTRAID_TENANT_ID')
this.MICROSOFT_ENTRAID_allowedAlgs = await this.secretService.get('MICROSOFT_ENTRAID_ALLOWED_ALGS')
this.MICROSOFT_ENTRAID_issuer = `https://login.microsoftonline.com/${this.MICROSOFT_ENTRAID_tenantId}/v2.0`;
this.MICROSOFT_ENTRAID_jwksUri = `https://login.microsoftonline.com/${this.MICROSOFT_ENTRAID_tenantId}/discovery/v2.0/keys`;
this.MICROSOFT_ENTRAID_jwks = createRemoteJWKSet(new URL(this.MICROSOFT_ENTRAID_jwksUri), {
// cache: true,
cooldownDuration: 30_000, // 30s
timeoutDuration: 10_000, // 10s
});
}
/**
* Authorization: Bearer <token> 의 <token> 부분을 검증.
* - iss: v2.0 발급자
* - aud: Application ID URI와 정확히 일치해야 함
* - alg: RS256(기본)
*/
async verify(
token: string,
identityProvider: IdentityProviderName
): Promise<JWTVerifyResult<JWTPayload>> {
if (!token) {
throw new Error('Empty token');
}
// IdP별 설정 매핑
const providers = {
MICROSOFT_ENTRAID: {
jwks: this.MICROSOFT_ENTRAID_jwks,
issuer: this.MICROSOFT_ENTRAID_issuer,
audience: this.jwtClaimAudience,
extraValidate: (payload: JWTPayload) => {
// AAD v2 토큰 전용 추가 검증
if (payload['ver'] && payload['ver'] !== '2.0') {
throw new Error(`Unsupported AAD token version: ${payload['ver']}`);
}
if (payload['tid'] && payload['tid'] !== this.MICROSOFT_ENTRAID_tenantId) {
throw new Error(`Unexpected tenant: ${payload['tid']}`);
}
},
},
AMAZON_COGNITO: {
// 아래 3개 필드는 onModuleInit에서 Entra와 동일하게 준비해야 함
// this.AMAZON_COGNITO_jwks = createRemoteJWKSet(new URL(this.AMAZON_COGNITO_jwksUri), {...})
jwks: this['AMAZON_COGNITO_jwks'],
issuer: this['AMAZON_COGNITO_issuer'],
audience: this['AMAZON_COGNITO_audience'],
extraValidate: (payload: JWTPayload) => {
// 필요하면 Cognito 전용 검증(예: token_use, cognito:username 등) 추가
// if (payload['token_use'] && payload['token_use'] !== 'id' /* or 'access' */) { ... }
},
},
} as const;
const provider = providers[identityProvider];
if (!provider?.jwks || !provider?.issuer || !provider?.audience) {
throw new Error(`Identity provider not configured: ${identityProvider}`);
}
// 허용 알고리즘: 환경변수(콤마 구분) -> 기본값(['RS256'])
const allowedAlgs =
(this.MICROSOFT_ENTRAID_allowedAlgs
? this.MICROSOFT_ENTRAID_allowedAlgs.split(',').map(s => s.trim()).filter(Boolean)
: this.tokenSigningAlgValuesSupported) as string[];
const result = await jwtVerify(token, provider.jwks, {
issuer: provider.issuer,
audience: provider.audience,
algorithms: allowedAlgs,
clockTolerance: this.clockTolerance,
});
const { payload, protectedHeader } = result;
// 공통: alg 확인
if (!allowedAlgs.includes(protectedHeader.alg as string)) {
throw new Error(`Unexpected alg: ${protectedHeader.alg}`);
}
// 프로바이더별 추가 검증
provider.extraValidate?.(payload);
return result;
}
}
+4 -3
View File
@@ -1,12 +1,13 @@
import { Module, Global } from '@nestjs/common'; import { Module, Global } from '@nestjs/common';
import { SecretModule } from './secret/secret.module'; import { SecretModule } from './secret/secret.module';
import { DatabaseModule } from './database/database.module'; // import { DatabaseModule } from './database/database.module';
import { NatsModule } from './nats/nats.module'; import { NatsModule } from './nats/nats.module';
import { JwtService } from './auth/jwt.service';
@Global() @Global()
@Module({ @Module({
imports: [SecretModule, NatsModule], imports: [SecretModule, NatsModule],
providers: [], providers: [JwtService],
exports: [SecretModule, NatsModule], exports: [SecretModule, NatsModule, JwtService],
}) })
export class GlobalModule {} export class GlobalModule {}