├── .eslintrc.js ├── .github ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── on-push-publish-to-npm.yml │ ├── run-test.yml │ └── version-bump-publish.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── index.d.ts ├── index.js ├── package.json └── test └── auth.test.js /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: ['eslint:recommended', 'prettier'], // extending recommended config and config derived from eslint-config-prettier 3 | plugins: ['prettier'], // activating esling-plugin-prettier (--fix stuff) 4 | parserOptions: { 5 | ecmaVersion: 2017 6 | }, 7 | 8 | env: { 9 | es6: true, 10 | jest: true, 11 | node: true 12 | }, 13 | rules: { 14 | 'prettier/prettier': [ 15 | // customizing prettier rules (unfortunately not many of them are customizable) 16 | 'error', 17 | { 18 | singleQuote: true, 19 | trailingComma: 'none' 20 | } 21 | ], 22 | eqeqeq: ['error', 'always'] // adding some custom ESLint rules 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Thanks for choosing to contribute! 4 | 5 | The following are a set of guidelines to follow when contributing to this project. 6 | 7 | ## Code Of Conduct 8 | 9 | This project adheres to the Adobe [code of conduct](../CODE_OF_CONDUCT.md). By participating, 10 | you are expected to uphold this code. Please report unacceptable behavior to 11 | [Grp-opensourceoffice@adobe.com](mailto:Grp-opensourceoffice@adobe.com). 12 | 13 | ## Have A Question? 14 | 15 | Start by filing an issue. The existing committers on this project work to reach 16 | consensus around project direction and issue solutions within issue threads 17 | (when appropriate). 18 | 19 | ## Contributor License Agreement 20 | 21 | All third-party contributions to this project must be accompanied by a signed contributor 22 | license agreement. This gives Adobe permission to redistribute your contributions 23 | as part of the project. [Sign our CLA](http://opensource.adobe.com/cla.html). You 24 | only need to submit an Adobe CLA one time, so if you have submitted one previously, 25 | you are good to go! 26 | 27 | ## Code Reviews 28 | 29 | All submissions should come in the form of pull requests and need to be reviewed 30 | by project committers. Read [GitHub's pull request documentation](https://help.github.com/articles/about-pull-requests/) 31 | for more information on sending pull requests. 32 | 33 | Lastly, please follow the [pull request template](PULL_REQUEST_TEMPLATE.md) when 34 | submitting a pull request! 35 | 36 | ## From Contributor To Committer 37 | 38 | We love contributions from our community! If you'd like to go a step beyond contributor 39 | and become a committer with full write access and a say in the project, you must 40 | be invited to the project. The existing committers employ an internal nomination 41 | process that must reach lazy consensus (silence is approval) before invitations 42 | are issued. If you feel you are qualified and want to get more deeply involved, 43 | feel free to reach out to existing committers to have a conversation about that. 44 | 45 | ## Security Issues 46 | 47 | Security issues shouldn't be reported on this issue tracker. Instead, [file an issue to our security experts](https://helpx.adobe.com/security/alertus.html) 48 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ### Expected Behaviour 5 | 6 | ### Actual Behaviour 7 | 8 | ### Reproduce Scenario (including but not limited to) 9 | 10 | #### Steps to Reproduce 11 | 12 | #### Platform and Version 13 | 14 | #### Sample Code that illustrates the problem 15 | 16 | #### Logs taken while reproducing problem 17 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Description 4 | 5 | 6 | 7 | ## Related Issue 8 | 9 | 10 | 11 | 12 | 13 | 14 | ## Motivation and Context 15 | 16 | 17 | 18 | ## How Has This Been Tested? 19 | 20 | 21 | 22 | 23 | 24 | ## Screenshots (if appropriate): 25 | 26 | ## Types of changes 27 | 28 | 29 | 30 | - [ ] Bug fix (non-breaking change which fixes an issue) 31 | - [ ] New feature (non-breaking change which adds functionality) 32 | - [ ] Breaking change (fix or feature that would cause existing functionality to change) 33 | 34 | ## Checklist: 35 | 36 | 37 | 38 | 39 | - [ ] I have signed the [Adobe Open Source CLA](http://opensource.adobe.com/cla.html). 40 | - [ ] My code follows the code style of this project. 41 | - [ ] My change requires a change to the documentation. 42 | - [ ] I have updated the documentation accordingly. 43 | - [ ] I have read the **CONTRIBUTING** document. 44 | - [ ] I have added tests to cover my changes. 45 | - [ ] All new and existing tests passed. 46 | -------------------------------------------------------------------------------- /.github/workflows/on-push-publish-to-npm.yml: -------------------------------------------------------------------------------- 1 | name: on-push-publish-to-npm 2 | on: 3 | push: 4 | branches: 5 | - master # Change this if not your default branch 6 | paths: 7 | - 'package.json' 8 | jobs: 9 | publish: 10 | if: github.repository == 'adobe/jwt-auth' 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v2 14 | - uses: actions/setup-node@v1 15 | with: 16 | node-version: 16 17 | - run: npm install 18 | - run: npm test 19 | - uses: JS-DevTools/npm-publish@v1 20 | with: 21 | token: ${{ secrets.ADOBE_BOT_NPM_TOKEN }} 22 | -------------------------------------------------------------------------------- /.github/workflows/run-test.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Node.js CI 5 | 6 | on: 7 | push: 8 | branches: [master] 9 | pull_request: 10 | branches: [master] 11 | 12 | jobs: 13 | build: 14 | runs-on: ubuntu-latest 15 | 16 | strategy: 17 | matrix: 18 | node-version: [14.x, 16.x, 18.x] 19 | # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ 20 | 21 | steps: 22 | - uses: actions/checkout@v2 23 | - name: Use Node.js ${{ matrix.node-version }} 24 | uses: actions/setup-node@v1 25 | with: 26 | node-version: ${{ matrix.node-version }} 27 | - run: npm install 28 | - run: npm run build --if-present 29 | - run: npm test 30 | -------------------------------------------------------------------------------- /.github/workflows/version-bump-publish.yml: -------------------------------------------------------------------------------- 1 | name: version-bump-publish 2 | on: 3 | workflow_dispatch: 4 | inputs: 5 | level: 6 | description: " | major | minor | patch | premajor | preminor | prepatch | prerelease" 7 | required: true 8 | default: "patch" 9 | tag: 10 | description: "The tag to publish to." 11 | required: false 12 | default: "latest" 13 | jobs: 14 | checkout: 15 | name: checkout 16 | runs-on: ubuntu-latest 17 | steps: 18 | - uses: actions/checkout@v2 19 | with: 20 | token: ${{ secrets.ADOBE_BOT_GITHUB_TOKEN }} 21 | - name: Configure CI Git User 22 | run: | 23 | git config user.name adobe-bot 24 | git config user.email grp-opensourceoffice@adobe.com 25 | - uses: actions/setup-node@v1 26 | with: 27 | node-version: 16 28 | - run: | 29 | npm install 30 | npm test 31 | - name: bump and pub 32 | if: ${{ github.event.inputs.level != '' }} 33 | run: | 34 | npm version ${{ github.event.inputs.level }} 35 | git push 36 | - uses: JS-DevTools/npm-publish@v1 37 | with: 38 | token: ${{ secrets.ADOBE_BOT_NPM_TOKEN }} 39 | tag: ${{ github.event.inputs.tag }} 40 | access: "public" 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/node 3 | # Edit at https://www.gitignore.io/?templates=node 4 | 5 | ### Node ### 6 | # Logs 7 | logs 8 | *.log 9 | npm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | 13 | # Runtime data 14 | pids 15 | *.pid 16 | *.seed 17 | *.pid.lock 18 | 19 | # Directory for instrumented libs generated by jscoverage/JSCover 20 | lib-cov 21 | 22 | # Coverage directory used by tools like istanbul 23 | coverage 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # Optional npm cache directory 48 | .npm 49 | 50 | # Optional eslint cache 51 | .eslintcache 52 | 53 | # Optional REPL history 54 | .node_repl_history 55 | 56 | # Output of 'npm pack' 57 | *.tgz 58 | 59 | # Yarn Integrity file 60 | .yarn-integrity 61 | 62 | # dotenv environment variables file 63 | .env 64 | .env.test 65 | 66 | # parcel-bundler cache (https://parceljs.org/) 67 | .cache 68 | 69 | # next.js build output 70 | .next 71 | 72 | # nuxt.js build output 73 | .nuxt 74 | 75 | # vuepress build output 76 | .vuepress/dist 77 | 78 | # Serverless directories 79 | .serverless/ 80 | 81 | # FuseBox cache 82 | .fusebox/ 83 | 84 | # DynamoDB Local files 85 | .dynamodb/ 86 | 87 | # End of https://www.gitignore.io/api/node 88 | 89 | # test files 90 | demo.js 91 | 92 | package-lock.json -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Adobe Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | - Using welcoming and inclusive language 18 | - Being respectful of differing viewpoints and experiences 19 | - Gracefully accepting constructive criticism 20 | - Focusing on what is best for the community 21 | - Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | - The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | - Trolling, insulting/derogatory comments, and personal or political attacks 28 | - Public or private harassment 29 | - Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | - Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at Grp-opensourceoffice@adobe.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [https://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: https://contributor-covenant.org 74 | [version]: https://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 Adobe 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Version](https://img.shields.io/npm/v/@adobe/jwt-auth.svg)](https://npmjs.org/package/@adobe/jwt-auth) 2 | [![Downloads/week](https://img.shields.io/npm/dw/@adobe/jwt-auth.svg)](https://npmjs.org/package/@adobe/jwt-auth) 3 | [![codecov](https://codecov.io/gh/adobe/jwt-auth/branch/master/graph/badge.svg)](https://codecov.io/gh/adobe/jwt-auth) 4 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 5 | [![Language grade: JavaScript](https://img.shields.io/lgtm/grade/javascript/g/adobe/jwt-auth.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/adobe/jwt-auth/context:javascript) 6 | 7 | # jwt-auth 8 | 9 | Retrieve an Adobe bearer token via the JWT path 10 | 11 | ## Goals 12 | 13 | Instead of every developer who wants to use the JWT Auth flow to retrieve an auth token from Adobe having to write their own implementation of this flow this package is intended to replace this need with one method call. 14 | 15 | ### Installation 16 | 17 | Instructions for how to download/install the code onto your machine. 18 | 19 | Example: 20 | 21 | ``` 22 | npm install @adobe/jwt-auth 23 | ``` 24 | 25 | ### Common Usage 26 | 27 | Usage instructions for your code. 28 | 29 | Promise based example: 30 | 31 | ```javascript 32 | const auth = require("@adobe/jwt-auth"); 33 | 34 | auth(config) 35 | .then((tokenResponse) => console.log(tokenResponse)) 36 | .catch((error) => console.log(error)); 37 | ``` 38 | 39 | Async/Await based example: 40 | 41 | ```javascript 42 | const auth = require("@adobe/jwt-auth"); 43 | 44 | let tokenResponse = await auth(config); 45 | console.log(tokenResponse); 46 | ``` 47 | 48 | or (if you don't care about the other properties in the token response) 49 | 50 | ```javascript 51 | const auth = require("@adobe/jwt-auth"); 52 | 53 | let { access_token } = await auth(config); 54 | console.log(access_token); 55 | ``` 56 | 57 | #### Config object 58 | 59 | The config object is where you pass in all the required and optional parameters to the `auth` call. 60 | 61 | | parameter | integration name | required | type | default | 62 | | ------------------ | -------------------- | -------- | --------------------------------- | ------------------------------ | 63 | | clientId | API Key (Client ID) | true | String | | 64 | | technicalAccountId | Technical account ID | true | String | | 65 | | orgId | Organization ID | true | String | | 66 | | clientSecret | Client secret | true | String | | 67 | | privateKey | | true | String | | 68 | | passphrase | | false | String | | 69 | | metaScopes | | true | Comma separated Sting or an Array | | 70 | | ims | | false | String | https://ims-na1.adobelogin.com | 71 | 72 | In order to determine which **metaScopes** you need to register for you can look them up by product in this [handy table](https://www.adobe.io/authentication/auth-methods.html#!AdobeDocs/adobeio-auth/master/JWT/Scopes.md). 73 | 74 | For instance if you need to be authenticated to call API's for both GDPR and User Management you would [look them up](https://www.adobe.io/authentication/auth-methods.html#!AdobeDocs/adobeio-auth/master/JWT/Scopes.md) and find that they are: 75 | 76 | - GDPR: https://ims-na1.adobelogin.com/s/ent_gdpr_sdk 77 | - User Management: https://ims-na1.adobelogin.com/s/ent_user_sdk 78 | 79 | They you would create an array of **metaScopes** as part of the config object. For instance: 80 | 81 | ```javascript 82 | const config = { 83 | clientId: "asasdfasf", 84 | clientSecret: "aslfjasljf-=asdfalasjdf==asdfa", 85 | technicalAccountId: "asdfasdfas@techacct.adobe.com", 86 | orgId: "asdfasdfasdf@AdobeOrg", 87 | metaScopes: [ 88 | "https://ims-na1.adobelogin.com/s/ent_gdpr_sdk", 89 | "https://ims-na1.adobelogin.com/s/ent_user_sdk", 90 | ], 91 | }; 92 | ``` 93 | 94 | However, if you omit the IMS url the package will automatically add it for you when making the call to generate the JWT. For example: 95 | 96 | ```javascript 97 | const config = { 98 | clientId: "asasdfasf", 99 | clientSecret: "aslfjasljf-=asdfalasjdf==asdfa", 100 | technicalAccountId: "asdfasdfas@techacct.adobe.com", 101 | orgId: "asdfasdfasdf@AdobeOrg", 102 | metaScopes: ["ent_gdpr_sdk", "ent_user_sdk"], 103 | }; 104 | ``` 105 | 106 | This is the recommended approach. 107 | 108 | #### Response Object 109 | 110 | The response object contains three keys: 111 | 112 | - `token_type` 113 | - `access_token` 114 | - `expires_in` 115 | 116 | #### Example 117 | 118 | ```javascript 119 | const auth = require("@adobe/jwt-auth"); 120 | const fs = require("fs"); 121 | 122 | const config = { 123 | clientId: "asasdfasf", 124 | clientSecret: "aslfjasljf-=asdfalasjdf==asdfa", 125 | technicalAccountId: "asdfasdfas@techacct.adobe.com", 126 | orgId: "asdfasdfasdf@AdobeOrg", 127 | metaScopes: ["ent_dataservices_sdk"], 128 | }; 129 | config.privateKey = fs.readFileSync("private.key"); 130 | 131 | auth(config) 132 | .then((token) => console.log(token)) 133 | .catch((error) => console.log(error)); 134 | ``` 135 | 136 | ### Contributing 137 | 138 | Contributions are welcomed! Read the [Contributing Guide](.github/CONTRIBUTING.md) for more information. 139 | 140 | ### Licensing 141 | 142 | This project is licensed under the Apache V2 License. See [LICENSE](LICENSE) for more information. 143 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Adobe. All rights reserved. 3 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. You may obtain a copy 5 | of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software distributed under 8 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 | OF ANY KIND, either express or implied. See the License for the specific language 10 | governing permissions and limitations under the License. 11 | */ 12 | 13 | // Type definitions for @adobe/jwt-auth 0.3 14 | // Project: https://github.com/adobe/jwt-auth#readme 15 | 16 | export = authorize; 17 | 18 | declare function authorize( 19 | options: authorize.JWTAuthConfig 20 | ): Promise; 21 | 22 | declare namespace authorize { 23 | export interface JWTAuthConfig { 24 | clientId: string; 25 | technicalAccountId: string; 26 | orgId: string; 27 | clientSecret: string; 28 | privateKey: string; 29 | passphrase?: string; 30 | metaScopes: string | string[]; 31 | ims?: string; 32 | } 33 | 34 | export interface JWTAuthResponse { 35 | token_type: "bearer"; 36 | access_token: string; 37 | expires_in: number; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Adobe. All rights reserved. 3 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. You may obtain a copy 5 | of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software distributed under 8 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 | OF ANY KIND, either express or implied. See the License for the specific language 10 | governing permissions and limitations under the License. 11 | */ 12 | 13 | const fetch = require('node-fetch'); 14 | const jwt = require('jsonwebtoken'); 15 | const FormData = require('form-data'); 16 | 17 | const MISSING_PARAMS = 'missing_params'; 18 | const SIGN_FAILED = 'sign_failed'; 19 | const REQUEST_FAILED = 'request_failed'; 20 | const UNEXPECTED_RESPONSE_BODY = 'invalid_response_body'; 21 | 22 | const throwRequestFailedError = details => { 23 | const error = new Error( 24 | `Request failed while swapping the jwt token. ${details}` 25 | ); 26 | error.code = REQUEST_FAILED; 27 | throw error; 28 | }; 29 | 30 | const throwUnexpectedResponseError = details => { 31 | const error = new Error( 32 | `Unexpected response received while swapping the jwt token. ${details}` 33 | ); 34 | error.code = UNEXPECTED_RESPONSE_BODY; 35 | throw error; 36 | }; 37 | 38 | async function authorize(options) { 39 | let { 40 | clientId, 41 | technicalAccountId, 42 | orgId, 43 | clientSecret, 44 | privateKey, 45 | passphrase = '', 46 | metaScopes, 47 | ims = 'https://ims-na1.adobelogin.com' 48 | } = options; 49 | 50 | const errors = []; 51 | !clientId ? errors.push('clientId') : ''; 52 | !technicalAccountId ? errors.push('technicalAccountId') : ''; 53 | !orgId ? errors.push('orgId') : ''; 54 | !clientSecret ? errors.push('clientSecret') : ''; 55 | !privateKey ? errors.push('privateKey') : ''; 56 | !metaScopes || metaScopes.length === 0 ? errors.push('metaScopes') : ''; 57 | if (errors.length > 0) { 58 | const missingParamsError = new Error( 59 | `Required parameter(s) ${errors.join(', ')} are missing` 60 | ); 61 | missingParamsError.code = MISSING_PARAMS; 62 | throw missingParamsError; 63 | } 64 | 65 | if (metaScopes.constructor !== Array) { 66 | metaScopes = metaScopes.split(','); 67 | } 68 | 69 | const jwtPayload = { 70 | exp: Math.round(300 + Date.now() / 1000), 71 | iss: orgId, 72 | sub: technicalAccountId, 73 | aud: `${ims}/c/${clientId}` 74 | }; 75 | 76 | for (let i = 0; i < metaScopes.length; i++) { 77 | if (metaScopes[i].indexOf('https') > -1) { 78 | jwtPayload[metaScopes[i]] = true; 79 | } else { 80 | jwtPayload[`${ims}/s/${metaScopes[i]}`] = true; 81 | } 82 | } 83 | 84 | let token; 85 | try { 86 | token = jwt.sign( 87 | jwtPayload, 88 | { key: privateKey, passphrase }, 89 | { algorithm: 'RS256' } 90 | ); 91 | } catch (tokenError) { 92 | tokenError.code = SIGN_FAILED; 93 | throw tokenError; 94 | } 95 | 96 | const form = new FormData(); 97 | form.append('client_id', clientId); 98 | form.append('client_secret', clientSecret); 99 | form.append('jwt_token', token); 100 | 101 | const postOptions = { 102 | method: 'POST', 103 | body: form, 104 | headers: form.getHeaders() 105 | }; 106 | 107 | return fetch(`${ims}/ims/exchange/jwt/`, postOptions) 108 | .catch(e => throwRequestFailedError(e.message)) 109 | .then(res => { 110 | return res.json().then(data => { 111 | return { 112 | ok: res.ok, 113 | json: data 114 | }; 115 | }); 116 | }) 117 | .then(({ ok, json }) => { 118 | const { access_token, error, error_description } = json; 119 | if (ok && access_token) { 120 | return json; 121 | } 122 | 123 | if (error && error_description) { 124 | const swapError = new Error(error_description); 125 | swapError.code = error; 126 | throw swapError; 127 | } else { 128 | throwUnexpectedResponseError( 129 | `The response body is as follows: ${JSON.stringify(json)}` 130 | ); 131 | } 132 | }); 133 | } 134 | 135 | module.exports = authorize; 136 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@adobe/jwt-auth", 3 | "version": "2.0.0", 4 | "description": "Retrieve an authorization token from Adobe via JSON Web Token", 5 | "main": "index.js", 6 | "types": "index.d.ts", 7 | "repository": { 8 | "type": "git", 9 | "url": "https://github.com/adobe/jwt-auth.git" 10 | }, 11 | "bugs": { 12 | "url": "https://github.com/adobe/jwt-auth/issues" 13 | }, 14 | "engines": { 15 | "node": "^14.18 || ^16.13 || >=18" 16 | }, 17 | "scripts": { 18 | "lint": "eslint test index.js", 19 | "test": "jest" 20 | }, 21 | "keywords": [ 22 | "jwt" 23 | ], 24 | "author": "Adobe Inc.", 25 | "license": "Apache-2.0", 26 | "dependencies": { 27 | "form-data": "^3.0.0", 28 | "jsonwebtoken": "^9.0.0", 29 | "node-fetch": "^2.6.1" 30 | }, 31 | "devDependencies": { 32 | "eslint": "^6.1.0", 33 | "eslint-config-prettier": "^6.0.0", 34 | "eslint-plugin-prettier": "^3.1.0", 35 | "eslint-utils": ">=1.4.1", 36 | "jest": "^29.5.0", 37 | "prettier": "^2.0.0" 38 | }, 39 | "jest": { 40 | "coverageDirectory": "./coverage/", 41 | "collectCoverage": true 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /test/auth.test.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Adobe. All rights reserved. 3 | This file is licensed to you under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. You may obtain a copy 5 | of the License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | Unless required by applicable law or agreed to in writing, software distributed under 8 | the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS 9 | OF ANY KIND, either express or implied. See the License for the specific language 10 | governing permissions and limitations under the License. 11 | */ 12 | 13 | // MOCKS //////////////////////////////////////////// 14 | 15 | const mockAccessToken = 'asdasdasd'; 16 | 17 | let jwt = require('jsonwebtoken'); 18 | let jwtActual = jest.requireActual('jsonwebtoken'); 19 | jest.mock('jsonwebtoken', () => jest.fn()); 20 | 21 | let mockResultSuccess = Promise.resolve({ 22 | ok: true, 23 | json: () => 24 | Promise.resolve({ access_token: mockAccessToken, expires_in: 123456 }) 25 | }); 26 | // attempting to contact the API threw an error 27 | let mockEndpointFailure = Promise.reject(new Error('500 error from server.')); 28 | // simple API failure, likely a customer issue 29 | let mockResultFailure = Promise.resolve({ 30 | ok: false, 31 | status: 400, 32 | json: () => 33 | Promise.resolve({ 34 | error: 'my_error_code', 35 | error_description: 'This is the error description. Customer issue.' 36 | }) 37 | }); 38 | // no access token, error, or error_description 39 | let mockResultFailureMalformedServerResponse = Promise.resolve({ 40 | ok: true, 41 | status: 200, 42 | json: () => Promise.resolve({ foo: 'bar', baz: 'faz' }) 43 | }); 44 | // good API call, but got an error with no access token 45 | let mockResultFailureNoJWT = Promise.resolve({ 46 | ok: true, 47 | status: 200, 48 | json: () => 49 | Promise.resolve({ 50 | error: 'my_error_code_no_jwt', 51 | error_description: 'This is the error description. No JWT present.' 52 | }) 53 | }); 54 | 55 | let fetch = require('node-fetch'); 56 | jest.mock('node-fetch', () => jest.fn()); 57 | 58 | // //////////////////////////////////////////// 59 | 60 | const auth = require('../index'); 61 | 62 | const clientId = 'xxxxxxxxxxxxxxxxxxxxxx'; 63 | const clientSecret = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'; 64 | const technicalAccountId = 'xxxxxxxxxxxxxxxxxxxxxx@techacct.adobe.com'; 65 | const orgId = 'xxxxxxxxxxxxxxxxxxxxxx@AdobeOrg'; 66 | const metaScopes = ['ent_dataservices_sdk']; 67 | const privateKey = 'aalsdjfajsldjfalsjkdfa;lsjf;aljs'; 68 | 69 | describe('Validate input', () => { 70 | test('all parameters missing', () => { 71 | expect.assertions(1); 72 | return expect(auth({})).rejects.toThrow( 73 | 'Required parameter(s) clientId, technicalAccountId, orgId, clientSecret, privateKey, metaScopes are missing' 74 | ); 75 | }); 76 | test('missing clientId', () => { 77 | expect.assertions(1); 78 | return expect( 79 | auth({ clientSecret, technicalAccountId, orgId, metaScopes, privateKey }) 80 | ).rejects.toThrow('Required parameter(s) clientId are missing'); 81 | }); 82 | test('missing clientSecret', () => { 83 | expect.assertions(1); 84 | return expect( 85 | auth({ clientId, technicalAccountId, orgId, metaScopes, privateKey }) 86 | ).rejects.toThrow('Required parameter(s) clientSecret are missing'); 87 | }); 88 | test('missing technicalAccountId', () => { 89 | expect.assertions(1); 90 | return expect( 91 | auth({ 92 | clientId, 93 | clientSecret, 94 | orgId, 95 | metaScopes, 96 | privateKey 97 | }) 98 | ).rejects.toThrow('Required parameter(s) technicalAccountId are missing'); 99 | }); 100 | test('missing orgId', () => { 101 | expect.assertions(1); 102 | return expect( 103 | auth({ 104 | clientId, 105 | clientSecret, 106 | technicalAccountId, 107 | metaScopes, 108 | privateKey 109 | }) 110 | ).rejects.toThrow('Required parameter(s) orgId are missing'); 111 | }); 112 | test('missing metaScopes', () => { 113 | expect.assertions(1); 114 | return expect( 115 | auth({ 116 | clientId, 117 | clientSecret, 118 | technicalAccountId, 119 | orgId, 120 | privateKey 121 | }) 122 | ).rejects.toThrow('Required parameter(s) metaScopes are missing'); 123 | }); 124 | test('missing privateKey', () => { 125 | expect.assertions(1); 126 | return expect( 127 | auth({ 128 | clientId, 129 | clientSecret, 130 | technicalAccountId, 131 | orgId, 132 | metaScopes 133 | }) 134 | ).rejects.toThrow('Required parameter(s) privateKey are missing'); 135 | }); 136 | }); 137 | 138 | describe('Sign with invalid primary key', () => { 139 | beforeEach(() => { 140 | jwt.sign = jest.fn().mockImplementation((...args) => { 141 | // call actual jwt module, not mocked version 142 | return jwtActual.sign(...args); 143 | }); 144 | }); 145 | 146 | afterEach(() => { 147 | jwt.sign.mockClear(); 148 | }); 149 | 150 | test('invalid primary key', () => { 151 | expect.assertions(1); 152 | return expect( 153 | auth({ 154 | clientId, 155 | clientSecret, 156 | technicalAccountId, 157 | orgId, 158 | metaScopes, 159 | privateKey 160 | }) 161 | ).rejects.toThrowError('secretOrPrivateKey is not valid key material'); 162 | }); 163 | }); 164 | 165 | describe('Fetch jwt', () => { 166 | beforeEach(() => { 167 | jwt.sign = jest.fn().mockImplementation(() => { 168 | return 'my_jwt_token'; 169 | }); 170 | }); 171 | 172 | afterEach(() => { 173 | jwt.sign.mockClear(); 174 | }); 175 | 176 | test('valid jwt', () => { 177 | fetch.mockImplementation(() => mockResultSuccess); 178 | return expect( 179 | auth({ 180 | clientId, 181 | clientSecret, 182 | technicalAccountId, 183 | orgId, 184 | metaScopes, 185 | privateKey 186 | }) 187 | ).resolves.toEqual({ access_token: mockAccessToken, expires_in: 123456 }); 188 | }); 189 | 190 | test('valid jwt, qualified scopes', () => { 191 | fetch.mockImplementation(() => mockResultSuccess); 192 | const metaScopes = [ 193 | 'https://ims-na1.adobelogin.com/s/ent_dataservices_sdk' 194 | ]; 195 | jwt.sign = jest.fn().mockImplementation(payload => { 196 | expect(payload[metaScopes[0]]).toBe(true); 197 | return 'my_jwt_token'; 198 | }); 199 | 200 | return expect( 201 | auth({ 202 | clientId, 203 | clientSecret, 204 | technicalAccountId, 205 | orgId, 206 | metaScopes, 207 | privateKey 208 | }) 209 | ).resolves.toEqual({ access_token: mockAccessToken, expires_in: 123456 }); 210 | }); 211 | 212 | test('valid jwt, unqualified scopes', () => { 213 | fetch.mockImplementation(() => mockResultSuccess); 214 | const metaScopes = 'ent_dataservices_sdk,some_other_scope'; 215 | jwt.sign = jest.fn().mockImplementation(payload => { 216 | expect( 217 | payload['https://ims-na1.adobelogin.com/s/ent_dataservices_sdk'] 218 | ).toBe(true); 219 | expect(payload['https://ims-na1.adobelogin.com/s/some_other_scope']).toBe( 220 | true 221 | ); 222 | return 'my_jwt_token'; 223 | }); 224 | return expect( 225 | auth({ 226 | clientId, 227 | clientSecret, 228 | technicalAccountId, 229 | orgId, 230 | metaScopes, 231 | privateKey 232 | }) 233 | ).resolves.toEqual({ access_token: mockAccessToken, expires_in: 123456 }); 234 | }); 235 | 236 | test('endpoint error thrown, unknown reason', async () => { 237 | expect.assertions(2); 238 | fetch.mockImplementation(() => mockEndpointFailure); 239 | try { 240 | await auth({ 241 | clientId, 242 | clientSecret, 243 | technicalAccountId, 244 | orgId, 245 | metaScopes, 246 | privateKey 247 | }); 248 | } catch (e) { 249 | expect(e.message).toBe( 250 | 'Request failed while swapping the jwt token. 500 error from server.' 251 | ); 252 | expect(e.code).toBe('request_failed'); 253 | } 254 | }); 255 | 256 | test('invalid jwt, expected endpoint error', async () => { 257 | expect.assertions(1); 258 | fetch.mockImplementation(() => mockResultFailure); 259 | return expect( 260 | auth({ 261 | clientId, 262 | clientSecret, 263 | technicalAccountId, 264 | orgId, 265 | metaScopes, 266 | privateKey 267 | }) 268 | ).rejects.toThrow('This is the error description. Customer issue.'); 269 | }); 270 | 271 | test('malformed server response, dump entire json() call', async () => { 272 | expect.assertions(2); 273 | fetch.mockImplementation(() => mockResultFailureMalformedServerResponse); 274 | try { 275 | await auth({ 276 | clientId, 277 | clientSecret, 278 | technicalAccountId, 279 | orgId, 280 | metaScopes, 281 | privateKey 282 | }); 283 | } catch (e) { 284 | expect(e.message).toBe( 285 | 'Unexpected response received while swapping the jwt token. The response body is as follows: {"foo":"bar","baz":"faz"}' 286 | ); 287 | expect(e.code).toBe('invalid_response_body'); 288 | } 289 | }); 290 | 291 | test('no access token returned from IMS, valid server response', async () => { 292 | expect.assertions(2); 293 | fetch.mockImplementation(() => mockResultFailureNoJWT); 294 | try { 295 | await auth({ 296 | clientId, 297 | clientSecret, 298 | technicalAccountId, 299 | orgId, 300 | metaScopes, 301 | privateKey 302 | }); 303 | } catch (e) { 304 | expect(e.message).toBe('This is the error description. No JWT present.'); 305 | expect(e.code).toBe('my_error_code_no_jwt'); 306 | } 307 | }); 308 | }); 309 | --------------------------------------------------------------------------------