├── .github
├── semantic.yml
└── workflows
│ ├── release.yml
│ └── build.yml
├── tsconfig.cjs.json
├── tsconfig.esm.json
├── tsconfig.json
├── .releaserc.json
├── src
├── index.ts
└── sdk.ts
├── .gitignore
├── package.json
├── test
└── sdk.test.ts
├── README.md
└── LICENSE
/.github/semantic.yml:
--------------------------------------------------------------------------------
1 | # Always validate the PR title AND all the commits
2 | titleAndCommits: true
--------------------------------------------------------------------------------
/tsconfig.cjs.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig",
3 | "compilerOptions": {
4 | "target": "ES2017",
5 | "module": "CommonJS",
6 | "outDir": "lib/cjs"
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/tsconfig.esm.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig",
3 | "compilerOptions": {
4 | "target": "ES2017",
5 | "module": "ESNext",
6 | "outDir": "lib/esm"
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "ES6",
4 | "module": "CommonJS",
5 | "moduleResolution": "Node",
6 | "strict": true,
7 | "strictPropertyInitialization": false,
8 | "declaration": true,
9 | "downlevelIteration": true,
10 | "allowSyntheticDefaultImports": true,
11 | },
12 | "include": ["src/**/*"]
13 | }
14 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: Release
2 | on:
3 | push:
4 | branches:
5 | - master
6 | jobs:
7 | semantic-release:
8 | runs-on: ubuntu-latest
9 | steps:
10 | - uses: actions/checkout@v2
11 |
12 | - name: Run semantic-release
13 | if: github.event_name == 'push' && github.repository == 'casdoor/casdoor-js-sdk'
14 | run: yarn install && yarn semantic-release
15 | env:
16 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
17 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
18 |
--------------------------------------------------------------------------------
/.releaserc.json:
--------------------------------------------------------------------------------
1 | {
2 | "debug": true,
3 | "branches": [
4 | "+([0-9])?(.{+([0-9]),x}).x",
5 | "master",
6 | {
7 | "name": "rc"
8 | },
9 | {
10 | "name": "beta",
11 | "prerelease": true
12 | },
13 | {
14 | "name": "alpha",
15 | "prerelease": true
16 | }
17 | ],
18 | "plugins": [
19 | "@semantic-release/commit-analyzer",
20 | "@semantic-release/release-notes-generator",
21 | "@semantic-release/npm",
22 | "@semantic-release/github"
23 | ]
24 | }
25 |
--------------------------------------------------------------------------------
/.github/workflows/build.yml:
--------------------------------------------------------------------------------
1 | name: Build
2 |
3 | on: [push, pull_request]
4 |
5 | jobs:
6 | build:
7 | name: SDK build
8 | runs-on: ubuntu-latest
9 | steps:
10 | - uses: actions/checkout@v2
11 | - uses: actions/setup-node@v2
12 | with:
13 | node-version: '18'
14 |
15 | - run: yarn install
16 |
17 | - run: yarn test
18 |
19 | - run: yarn coverage
20 |
21 | - run: yarn build
22 |
23 | - name: Codecov
24 | uses: codecov/codecov-action@v1
25 | with:
26 | token: ${{ secrets.CODECOV_TOKEN }}
27 |
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | // Copyright 2021 The Casdoor Authors. All Rights Reserved.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | import Sdk from './sdk';
16 |
17 | export default Sdk;
18 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 | lerna-debug.log*
8 |
9 | # Diagnostic reports (https://nodejs.org/api/report.html)
10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
11 |
12 | # Runtime data
13 | pids
14 | *.pid
15 | *.seed
16 | *.pid.lock
17 |
18 | # Directory for instrumented libs generated by jscoverage/JSCover
19 | lib-cov
20 |
21 | # Coverage directory used by tools like istanbul
22 | coverage
23 | *.lcov
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 | # TypeScript cache
48 | *.tsbuildinfo
49 |
50 | # Optional npm cache directory
51 | .npm
52 |
53 | # Optional eslint cache
54 | .eslintcache
55 |
56 | # Microbundle cache
57 | .rpt2_cache/
58 | .rts2_cache_cjs/
59 | .rts2_cache_es/
60 | .rts2_cache_umd/
61 |
62 | # Optional REPL history
63 | .node_repl_history
64 |
65 | # Output of 'npm pack'
66 | *.tgz
67 |
68 | # Yarn Integrity file
69 | .yarn-integrity
70 |
71 | # dotenv environment variables file
72 | .env
73 | .env.test
74 |
75 | # parcel-bundler cache (https://parceljs.org/)
76 | .cache
77 |
78 | # Next.js build output
79 | .next
80 |
81 | # Nuxt.js build / generate output
82 | .nuxt
83 | dist
84 |
85 | # Gatsby files
86 | .cache/
87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js
88 | # https://nextjs.org/blog/next-9-1#public-directory-support
89 | # public
90 |
91 | # vuepress build output
92 | .vuepress/dist
93 |
94 | # Serverless directories
95 | .serverless/
96 |
97 | # FuseBox cache
98 | .fusebox/
99 |
100 | # DynamoDB Local files
101 | .dynamodb/
102 |
103 | # TernJS port file
104 | .tern-port
105 |
106 | .idea/
107 | lib/
108 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "casdoor-js-sdk",
3 | "version": "0.0.1",
4 | "description": "Javascript client SDK for Casdoor",
5 | "main": "lib/cjs/index.js",
6 | "typings": "lib/cjs/index.d.ts",
7 | "module": "lib/esm/index.js",
8 | "license": "Apache-2.0",
9 | "scripts": {
10 | "prepack": "run-s build",
11 | "postpack": "run-s clean",
12 | "build": "run-s clean && run-p build:*",
13 | "build:cjs": "tsc -p tsconfig.cjs.json",
14 | "build:esm": "tsc -p tsconfig.esm.json",
15 | "clean": "rimraf lib",
16 | "test": "jest",
17 | "coverage": "jest --coverage",
18 | "semantic-release": "semantic-release"
19 | },
20 | "jest": {
21 | "maxConcurrency": 1,
22 | "maxWorkers": 1,
23 | "testTimeout": 30000,
24 | "testEnvironment": "jsdom",
25 | "transform": {
26 | "^.+\\.(t|j)sx?$": "ts-jest"
27 | },
28 | "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
29 | "moduleFileExtensions": [
30 | "ts",
31 | "tsx",
32 | "js",
33 | "jsx",
34 | "json",
35 | "node"
36 | ]
37 | },
38 | "devDependencies": {
39 | "@semantic-release/changelog": "^5.0.1",
40 | "@semantic-release/commit-analyzer": "^8.0.1",
41 | "@semantic-release/git": "^9.0.0",
42 | "@semantic-release/github": "^7.2.3",
43 | "@semantic-release/npm": "^7.1.3",
44 | "@semantic-release/release-notes-generator": "^9.0.3",
45 | "@types/jest": "^27.0.2",
46 | "jest": "^27.2.1",
47 | "npm-run-all": "^4.1.5",
48 | "rimraf": "^3.0.2",
49 | "semantic-release": "19.0.3",
50 | "ts-jest": "^27.0.5",
51 | "typescript": "^4.5.5"
52 | },
53 | "files": [
54 | "lib"
55 | ],
56 | "keywords": [
57 | "auth",
58 | "authn",
59 | "authentication",
60 | "sso",
61 | "oauth",
62 | "oidc",
63 | "casbin",
64 | "casdoor"
65 | ],
66 | "repository": {
67 | "type": "git",
68 | "url": "https://github.com/casdoor/casdoor-js-sdk.git"
69 | },
70 | "author": {
71 | "name": "Zxilly",
72 | "email": "zxilly@outlook.com"
73 | },
74 | "bugs": {
75 | "url": "https://github.com/casdoor/casdoor-js-sdk/issues"
76 | },
77 | "homepage": "https://github.com/casdoor/casdoor-js-sdk",
78 | "dependencies": {
79 | "js-pkce": "^1.3.0",
80 | "jwt-decode": "^4.0.0"
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/test/sdk.test.ts:
--------------------------------------------------------------------------------
1 | // Copyright 2021 The Casdoor Authors. All Rights Reserved.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | import Sdk from '../src';
16 |
17 | const sdkConfig = {
18 | serverUrl: 'https://door.casbin.com',
19 | clientId: '014ae4bd048734ca2dea',
20 | appName: 'app-casnode',
21 | organizationName: 'casbin',
22 | redirectPath: '/callback',
23 | };
24 |
25 | describe('sdk constructor', () => {
26 | it('with full configs', () => {
27 | const sdk = new Sdk(sdkConfig);
28 |
29 | const instanceConfig = sdk['config'];
30 | expect(instanceConfig.serverUrl).toEqual(sdkConfig.serverUrl);
31 | expect(instanceConfig.clientId).toEqual(sdkConfig.clientId);
32 | expect(instanceConfig.appName).toEqual(sdkConfig.appName);
33 | expect(instanceConfig.organizationName).toEqual(sdkConfig.organizationName);
34 | expect(instanceConfig.redirectPath).toEqual(sdkConfig.redirectPath);
35 | });
36 |
37 | it('config withou redirectPath', () => {
38 | let config = {
39 | ...sdkConfig,
40 | redirectPath: undefined,
41 | };
42 | const sdk = new Sdk(sdkConfig);
43 |
44 | const instanceConfig = sdk['config'];
45 | expect(instanceConfig.redirectPath).toEqual('/callback');
46 | });
47 | });
48 |
49 | describe('getSigninUrl', () => {
50 | beforeEach(() => {
51 | sessionStorage.clear();
52 | });
53 |
54 | it('redirectPath with relative path', () => {
55 | const sdk = new Sdk(sdkConfig);
56 |
57 | expect(sdk.getSigninUrl()).toContain(
58 | `redirect_uri=${encodeURIComponent(
59 | window.location.origin + sdkConfig.redirectPath
60 | )}`
61 | );
62 | });
63 |
64 | it('redirectPath with fully path', () => {
65 | const config = {
66 | ...sdkConfig,
67 | redirectPath: 'http://localhost:6001/other-callback',
68 | };
69 | const sdk = new Sdk(config);
70 |
71 | expect(sdk.getSigninUrl()).toContain(
72 | `redirect_uri=${encodeURIComponent(config.redirectPath)}`
73 | );
74 | });
75 |
76 | it('with fixed state', () => {
77 | const state = 'test-state';
78 | const sdk = new Sdk(sdkConfig);
79 | sessionStorage.setItem('casdoor-state', state);
80 | expect(sdk.getSigninUrl()).toContain(`state=${state}`);
81 | });
82 |
83 | it('with random state', () => {
84 | const sdk = new Sdk(sdkConfig);
85 | const url = sdk.getSigninUrl();
86 | const state = sessionStorage.getItem('casdoor-state');
87 | expect(url).toContain(`state=${state}`);
88 | });
89 | });
90 |
91 | describe('parseAccessToken', () => {
92 | it('should correctly parse JWT token', () => {
93 | const sdk = new Sdk(sdkConfig);
94 |
95 | const accessToken = 'eyJhbGciOiJSUzI1NiIsImtpZCI6ImNlcnQtYnVpbHQtaW4iLCJ0eXAiOiJKV1QifQ.eyJvd25lciI6ImNhc2JpbiIsIm5hbWUiOiJhZG1pbiIsImNyZWF0ZWRUaW1lIjoiMjAyMC0wNy0xNlQyMTo0Njo1MiswODowMCIsInVwZGF0ZWRUaW1lIjoiMjAyNC0wMi0yMFQxMzo1MzoyNSswODowMCIsImRlbGV0ZWRUaW1lIjoiIiwiaWQiOiI5ZWIyMGY3OS0zYmI1LTRlNzQtOTlhYy0zOWUzYjlhMTcxZTgiLCJ0eXBlIjoibm9ybWFsLXVzZXIiLCJwYXNzd29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YXNkb29yLmNvbSIsInN1YiI6IjllYjIwZjc5LTNiYjUtNGU3NC05OWFjLTM5ZTNiOWExNzFlOCIsImF1ZCI6WyIwYmE1MjgxMjFlYTg3YjNlYjU0ZCJdLCJleHAiOjE3MDkwMjk2OTcsIm5iZiI6MTcwODQyNDg5NywiaWF0IjoxNzA4NDI0ODk3LCJqdGkiOiJhZG1pbi9kZmUzM2Y0Ny04NGRjLTQxZjktOWE4OC03ZTU0ZWEzZTY5MjEifQ.f4l-lys7e34QEih4tJR0v5JpbIg1I8ljFoOnDnTe141UJ_ux9k2WqqCCw5g3EqwHLpiSgf_Q3ut7hgL-Ga911fLzJhSWDxx5nLfoKlQUaEu8mtz8MdleVCCytxAMxzJkeXcA7ng_QcXIFfKTRp6v5nUo8bVCp8nFfP9DJUD4irhaEwZqzJ6Y6xZRkn1YZht0j2ey39trn3cjWozKvNQNc-nSEik0UlPUO-VnQi8GnEy19C8rT6YltbboOYbmk7x57vOwecDhfUYoNdlseB3Ac3TXAHGVeCLyZWnLzU8JHNClzqqI-pUXKfQ5OGTkEBG8J2CKuzTG9cgHyAk5pA-B8Ea38rP5CNiUCbsaLR5o8bs0krJ9UJx-b52W4n8pSJmUUiE4qDCe_piesLERrTnQszFT_pG6aF_o5w0UN5Mr0houkDsqwj2sNa4oTtvkz1JuYGn1fqQ89jvPp9bGemyuI-N_gCjRecn7TKW-_1MrOYExboGCUsftY8K42PYtrpXY3hCLWx2IamMrU8fSbAqkBZym02EHEKoroCw269ejtL93ZhC6-eyljLl_Fb5NjF9infGxCRjaFco5M6k_ELKwnA5V65-OmTpT6Ti3ws6zhfs27ClZbFdtUB-HcYSMGNrqZbFdmH7ne1sKinwFsH51JAKSCCXyJOZsHMQ-RmugOAA';
96 | const result = sdk.parseAccessToken(accessToken);
97 |
98 | expect(result.header.alg).toEqual("RS256");
99 | expect(result.header.kid).toEqual("cert-built-in");
100 | expect(result.header.typ).toEqual("JWT");
101 | expect(result.payload.owner).toEqual("casbin");
102 | expect(result.payload.name).toEqual("admin");
103 | });
104 | });
105 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # casdoor-js-sdk
2 |
3 | [![NPM version][npm-image]][npm-url]
4 | [![NPM download][download-image]][download-url]
5 | [](https://codebeat.co/projects/github-com-casdoor-casdoor-js-sdk-master)
6 | [](https://github.com/casdoor/casdoor-js-sdk/actions/workflows/release.yml)
7 | [](https://github.com/casdoor/casdoor-js-sdk/actions/workflows/build.yml)
8 | [](https://codecov.io/gh/casdoor/casdoor-js-sdk)
9 | [](https://github.com/casdoor/casdoor-js-sdk/releases/latest)
10 | [](https://discord.gg/5rPsrAzK7S)
11 |
12 | [npm-image]: https://img.shields.io/npm/v/casdoor-js-sdk.svg?style=flat-square
13 | [npm-url]: https://npmjs.com/package/casdoor-js-sdk
14 |
15 | [download-image]: https://img.shields.io/npm/dm/casdoor-js-sdk.svg?style=flat-square
16 | [download-url]: https://npmjs.com/package/casdoor-js-sdk
17 |
18 | This is Casdoor's SDK for js will allow you to easily connect your application to the [Casdoor authentication system](https://casdoor.org) without having to implement it from scratch.
19 |
20 | Casdoor SDK is very simple to use. We will show you the steps below.
21 |
22 | ## Usage in NPM environment
23 |
24 | ### Installation
25 |
26 | ~~~shell script
27 | # NPM
28 | npm i casdoor-js-sdk
29 |
30 | # Yarn
31 | yarn add casdoor-js-sdk
32 | ~~~
33 |
34 | ### Init SDK
35 |
36 | Initialization requires 5 parameters, which are all string type:
37 |
38 | | Name (in order) | Must | Description |
39 | |------------------|------|------------------------------------------------------------------------------------------------|
40 | | serverUrl | Yes | your Casdoor server URL |
41 | | clientId | Yes | the Client ID of your Casdoor application |
42 | | appName | Yes | the name of your Casdoor application |
43 | | organizationName | Yes | the name of the Casdoor organization connected with your Casdoor application |
44 | | redirectPath | No | the path of the redirect URL for your Casdoor application, will be `/callback` if not provided |
45 | | signinPath | No | the path of the signin URL for your Casdoor application, will be `/api/signin` if not provided |
46 |
47 | ```typescript
48 | import {SDK, SdkConfig} from 'casdoor-js-sdk'
49 |
50 | const sdkConfig: SdkConfig = {
51 | serverUrl: "https://door.casbin.com",
52 | clientId: "014ae4bd048734ca2dea",
53 | appName: "app-casnode",
54 | organizationName: "casbin",
55 | redirectPath: "/callback",
56 | signinPath: "/api/signin",
57 | }
58 | const sdk = new SDK(sdkConfig)
59 | // call sdk to handle
60 | ```
61 |
62 | ## Usage in vanilla Javascript
63 |
64 | ### Import and init SDK
65 |
66 | Initialization parameters are consistent with the previous node.js section:
67 |
68 | ```html
69 |
70 |
83 | ```
84 |
85 | ### Call functions in SDK
86 |
87 | ```html
88 |
93 | ```
94 |
95 | ## API reference interface
96 |
97 | #### Get sign up url
98 |
99 | ```typescript
100 | getSignupUrl(enablePassword)
101 | ```
102 |
103 | Return the casdoor url that navigates to the registration screen
104 |
105 | #### Get sign in url
106 |
107 | ```typescript
108 | getSigninUrl()
109 | ```
110 |
111 | Return the casdoor url that navigates to the login screen
112 |
113 | #### Get user profile page url
114 |
115 | ```typescript
116 | getUserProfileUrl(userName, account)
117 | ```
118 |
119 | Return the url to navigate to a specific user's casdoor personal page
120 |
121 | #### Get my profile page url
122 |
123 | ```typescript
124 | getMyProfileUrl(account)
125 | ```
126 |
127 | #### Sign in
128 |
129 | ```typescript
130 | signin(serverUrl, signinPath)
131 | ```
132 |
133 | Handle the callback url from casdoor, call the back-end api to complete the login process
134 |
135 | #### Determine whether silent sign-in is being used
136 |
137 | ```typescript
138 | isSilentSigninRequested()
139 | ```
140 |
141 | We usually use this method to determine if silent login is being used. By default, if the silentSignin parameter is included in the URL and equals one, this method will return true. Of course, you can also use any method you prefer.
142 |
143 | #### silentSignin
144 |
145 |
146 | ````typescript
147 | silentSignin(onSuccess, onFailure)
148 | ````
149 |
150 | First, let's explain the two parameters of this method, which are the callback methods for successful and failed login. Next, I will describe the execution process of this method. We will create a hidden "iframe" element to redirect to the login page for authentication, thereby achieving the effect of silent sign-in.
151 |
152 | #### popupSignin
153 |
154 |
155 | ````typescript
156 | popupSignin(serverUrl, signinPath)
157 | ````
158 | Popup a window to handle the callback url from casdoor, call the back-end api to complete the login process and store the token in localstorage, then reload the main window. See Demo: [casdoor-nodejs-react-example](https://github.com/casdoor/casdoor-nodejs-react-example).
159 |
160 | ### OAuth2 PKCE flow sdk (for SPA without backend)
161 |
162 | #### Start the authorization process
163 |
164 | Typically, you just need to go to the authorization url to start the process. This example is something that might work in an SPA.
165 |
166 | ```typescript
167 | signin_redirect();
168 | ```
169 |
170 | You may add additional query parameters to the authorize url by using an optional second parameter:
171 |
172 | ```typescript
173 | const additionalParams = {test_param: 'testing'};
174 | signin_redirect(additionalParams);
175 | ```
176 |
177 | #### Trade the code for a token
178 |
179 | When you get back here, you need to exchange the code for a token.
180 |
181 | ```typescript
182 | sdk.exchangeForAccessToken().then((resp) => {
183 | const token = resp.access_token;
184 | // Do stuff with the access token.
185 | });
186 | ```
187 |
188 | As with the authorizeUrl method, an optional second parameter may be passed to the exchangeForAccessToken method to send additional parameters to the request:
189 |
190 | ```typescript
191 | const additionalParams = {test_param: 'testing'};
192 |
193 | sdk.exchangeForAccessToken(additionalParams).then((resp) => {
194 | const token = resp.access_token;
195 | // Do stuff with the access token.
196 | });
197 | ```
198 |
199 | #### Parse the access token
200 |
201 | Once you have an access token, you can parse it into JWT header and payload.
202 |
203 | ```typescript
204 | const result = sdk.parseAccessToken(accessToken);
205 | console.log("JWT algorithm: " + result.header.alg);
206 | console.log("User organization: " + result.payload.owner);
207 | console.log("User name: " + result.payload.name);
208 | ```
209 |
210 | #### Get user info
211 |
212 | Once you have an access token, you can use it to get user info.
213 |
214 | ```typescript
215 | getUserInfo(accessToken).then((resp) => {
216 | const userInfo = resp;
217 | // Do stuff with the user info.
218 | });
219 | ```
220 |
221 | #### Refresh access token
222 |
223 | You could use a refresh token, to get a new token from the oauth server when token expired.
224 |
225 | ```typescript
226 | sdk.refreshAccessToken(refreshToken).then((resp) => {
227 | const token = resp.access_token;
228 | // Do stuff with new access token
229 | });
230 | ```
231 |
232 | #### A note on Storage
233 | By default, this package will use sessionStorage to persist the pkce_state. On (mostly) mobile devices there's a higher chance users are returning in a different browser tab. E.g. they kick off in a WebView & get redirected to a new tab. The sessionStorage will be empty there.
234 |
235 | In this case it you can opt in to use localStorage instead of sessionStorage:
236 |
237 | ```typescript
238 | import {SDK, SdkConfig} from 'casdoor-js-sdk'
239 |
240 | const sdkConfig = {
241 | // ...
242 | storage: localStorage, // any Storage object, sessionStorage (default) or localStorage
243 | }
244 |
245 | const sdk = new SDK(sdkConfig)
246 | ```
247 |
248 | ## More examples
249 |
250 | To see how to use casdoor frontend SDK with casdoor backend SDK, you can refer to examples below:
251 |
252 | [casnode](https://github.com/casbin/casnode): casdoor-js-sdk + casdoor-go-sdk
253 |
254 | [casdoor-python-vue-sdk-example](https://github.com/casdoor/casdoor-python-vue-sdk-example): casdoor-vue-sdk + casdoor-python-sdk
255 |
256 |
257 |
258 | A more detailed description can be moved to:[casdoor-sdk](https://casdoor.org/docs/how-to-connect/sdk)
259 |
--------------------------------------------------------------------------------
/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 [yyyy] [name of copyright owner]
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.
202 |
--------------------------------------------------------------------------------
/src/sdk.ts:
--------------------------------------------------------------------------------
1 | // Copyright 2021 The Casdoor Authors. All Rights Reserved.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | import PKCE from 'js-pkce';
16 | import ITokenResponse from "js-pkce/dist/ITokenResponse";
17 | import IObject from "js-pkce/dist/IObject";
18 | import {jwtDecode, JwtHeader} from "jwt-decode";
19 |
20 | export interface SdkConfig {
21 | serverUrl: string, // your Casdoor server URL, e.g., "https://door.casbin.com" for the official demo site
22 | clientId: string, // the Client ID of your Casdoor application, e.g., "014ae4bd048734ca2dea"
23 | appName: string, // the name of your Casdoor application, e.g., "app-casnode"
24 | organizationName: string // the name of the Casdoor organization connected with your Casdoor application, e.g., "casbin"
25 | redirectPath?: string // the path of the redirect URL for your Casdoor application, will be "/callback" if not provided
26 | signinPath?: string // the path of the signin URL for your Casdoor applcation, will be "/api/signin" if not provided
27 | scope?: string // apply for permission to obtain the user information, will be "profile" if not provided
28 | storage?: Storage // the storage to store the state, will be sessionStorage if not provided
29 | }
30 |
31 | // reference: https://github.com/casdoor/casdoor-go-sdk/blob/90fcd5646ec63d733472c5e7ce526f3447f99f1f/auth/jwt.go#L19-L32
32 | export interface Account {
33 | organization: string,
34 | username: string,
35 | type: string,
36 | name: string,
37 | avatar: string,
38 | email: string,
39 | phone: string,
40 | affiliation: string,
41 | tag: string,
42 | language: string,
43 | score: number,
44 | isAdmin: boolean,
45 | accessToken: string
46 | }
47 |
48 | export interface Role {
49 | owner: string,
50 | name: string,
51 | createdTime: string,
52 | displayName: string,
53 | description: string,
54 | roles: string[],
55 | domains: string[]
56 | isEnabled: boolean
57 | }
58 |
59 | export interface JwtPayload {
60 | owner: string;
61 | name: string;
62 | createdTime: string;
63 | updatedTime: string;
64 | deletedTime: string;
65 | id: string;
66 | type: string;
67 | password: string;
68 | passwordSalt: string;
69 | passwordType: string;
70 | displayName: string;
71 | firstName: string;
72 | lastName: string;
73 | avatar: string;
74 | avatarType: string;
75 | permanentAvatar: string;
76 | email: string;
77 | emailVerified: boolean;
78 | phone: string;
79 | countryCode: string;
80 | region: string;
81 | location: string;
82 | address: string[];
83 | affiliation: string;
84 | title: string;
85 | idCardType: string;
86 | idCard: string;
87 | homepage: string;
88 | bio: string;
89 | language: string;
90 | gender: string;
91 | birthday: string;
92 | education: string;
93 | score: number;
94 | karma: number;
95 | ranking: number;
96 | isDefaultAvatar: boolean;
97 | isOnline: boolean;
98 | isAdmin: boolean;
99 | isForbidden: boolean;
100 | isDeleted: boolean;
101 | signupApplication: string;
102 | hash: string;
103 | preHash: string;
104 | accessKey: string;
105 | accessSecret: string;
106 | github: string;
107 | google: string;
108 | qq: string;
109 | wechat: string;
110 | facebook: string;
111 | dingtalk: string;
112 | weibo: string;
113 | gitee: string;
114 | linkedin: string;
115 | wecom: string;
116 | lark: string;
117 | gitlab: string;
118 | createdIp: string;
119 | lastSigninTime: string;
120 | lastSigninIp: string;
121 | preferredMfaType: string;
122 | recoveryCodes: null | string[];
123 | totpSecret: string;
124 | mfaPhoneEnabled: boolean;
125 | mfaEmailEnabled: boolean;
126 | ldap: string;
127 | properties: Record;
128 | roles: Role[];
129 | permissions: Permission[];
130 | groups: string[];
131 | lastSigninWrongTime: string;
132 | signinWrongTimes: number;
133 | tokenType: string;
134 | tag: string;
135 | scope: string;
136 | iss: string;
137 | sub: string;
138 | aud: string[];
139 | exp: number;
140 | nbf: number;
141 | iat: number;
142 | jti: string;
143 | }
144 |
145 | export interface Permission {
146 | owner: string;
147 | name: string;
148 | createdTime: string;
149 | displayName: string;
150 | description: string;
151 | users: string[] | null;
152 | groups: string[];
153 | roles: string[];
154 | domains: string[];
155 | model: string;
156 | adapter: string;
157 | resourceType: string;
158 | resources: string[];
159 | actions: string[];
160 | effect: string;
161 | isEnabled: boolean;
162 | submitter: string;
163 | approver: string;
164 | approveTime: string;
165 | state: string;
166 | }
167 |
168 | class Sdk {
169 | private config: SdkConfig
170 | private pkce: PKCE
171 |
172 | constructor(config: SdkConfig) {
173 | this.config = config
174 | if (config.redirectPath === undefined || config.redirectPath === null) {
175 | this.config.redirectPath = "/callback";
176 | }
177 |
178 | if (config.scope === undefined || config.scope === null) {
179 | this.config.scope = "profile";
180 | }
181 |
182 | this.pkce = new PKCE({
183 | client_id: this.config.clientId,
184 | redirect_uri: `${window.location.origin}${this.config.redirectPath}`,
185 | authorization_endpoint: `${this.config.serverUrl.trim()}/login/oauth/authorize`,
186 | token_endpoint: `${this.config.serverUrl.trim()}/api/login/oauth/access_token`,
187 | requested_scopes: this.config.scope || "profile",
188 | storage: this.config.storage,
189 | });
190 | }
191 |
192 | getOrSaveState(): string {
193 | const state = sessionStorage.getItem("casdoor-state");
194 | if (state !== null) {
195 | return state;
196 | } else {
197 | const state = Math.random().toString(36).slice(2);
198 | sessionStorage.setItem("casdoor-state", state);
199 | return state;
200 | }
201 | }
202 |
203 | clearState() {
204 | sessionStorage.removeItem("casdoor-state");
205 | }
206 |
207 | public getSignupUrl(enablePassword: boolean = true): string {
208 | if (enablePassword) {
209 | sessionStorage.setItem("signinUrl", this.getSigninUrl());
210 | return `${this.config.serverUrl.trim()}/signup/${this.config.appName}`;
211 | } else {
212 | return this.getSigninUrl().replace("/login/oauth/authorize", "/signup/oauth/authorize");
213 | }
214 | }
215 |
216 | public getSigninUrl(): string {
217 | const redirectUri = this.config.redirectPath && this.config.redirectPath.includes('://') ? this.config.redirectPath : `${window.location.origin}${this.config.redirectPath}`;
218 | const state = this.getOrSaveState();
219 | return `${this.config.serverUrl.trim()}/login/oauth/authorize?client_id=${this.config.clientId}&response_type=code&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${this.config.scope}&state=${state}`;
220 | }
221 |
222 | public getUserProfileUrl(userName: string, account: Account): string {
223 | let param = "";
224 | if (account !== undefined && account !== null) {
225 | param = `?access_token=${account.accessToken}`;
226 | }
227 | return `${this.config.serverUrl.trim()}/users/${this.config.organizationName}/${userName}${param}`;
228 | }
229 |
230 | public getMyProfileUrl(account: Account, returnUrl: String = ""): string {
231 | let params = "";
232 | if (account !== undefined && account !== null) {
233 | params = `?access_token=${account.accessToken}`;
234 | if (returnUrl !== "") {
235 | params += `&returnUrl=${returnUrl}`;
236 | }
237 | } else if (returnUrl !== "") {
238 | params = `?returnUrl=${returnUrl}`;
239 | }
240 | return `${this.config.serverUrl.trim()}/account${params}`;
241 | }
242 |
243 | public async signin(serverUrl: string, signinPath?: string, code?: string, state?: string): Promise {
244 | if (!code || !state) {
245 | const params = new URLSearchParams(window.location.search);
246 | code = params.get("code")!;
247 | state = params.get("state")!;
248 | }
249 | const expectedState = this.getOrSaveState();
250 | this.clearState();
251 | if (state !== expectedState) {
252 | return new Promise((resolve, reject) => {
253 | setTimeout(() => {
254 | resolve({
255 | // @ts-ignore
256 | status: "error",
257 | msg: `invalid state parameter, expected: ${expectedState}, got: ${state}`,
258 | });
259 | }, 10);
260 | });
261 | }
262 |
263 | return fetch(`${serverUrl}${signinPath || this.config.signinPath || '/api/signin'}?code=${code}&state=${state}`, {
264 | method: "POST",
265 | credentials: "include",
266 | }).then(res => res.json());
267 | }
268 |
269 | public isSilentSigninRequested(): boolean {
270 | const params = new URLSearchParams(window.location.search);
271 | return params.get("silentSignin") === "1";
272 | }
273 |
274 | public silentSignin(onSuccess: (message: any) => void, onFailure: (message: any) => void) {
275 | const iframe = document.createElement('iframe');
276 | iframe.style.display = 'none';
277 | iframe.src = `${this.getSigninUrl()}&silentSignin=1`;
278 |
279 | const handleMessage = (event: MessageEvent) => {
280 | if (window !== window.parent) {
281 | return null;
282 | }
283 |
284 | const message = event.data;
285 | if (message.tag !== "Casdoor" || message.type !== "SilentSignin") {
286 | return;
287 | }
288 | if (message.data === 'success') {
289 | onSuccess(message);
290 | } else {
291 | onFailure(message);
292 | }
293 | };
294 | window.addEventListener('message', handleMessage);
295 | document.body.appendChild(iframe);
296 | }
297 |
298 | public async popupSignin(serverUrl: string, signinPath?: string, callback?: (info: any) => any,) {
299 | const width = 500;
300 | const height = 600;
301 | const left = window.screen.width / 2 - width / 2;
302 | const top = window.screen.height / 2 - height / 2;
303 | const popupWindow = window.open(this.getSigninUrl() + "&popup=1", "login", `width=${width},height=${height},top=${top},left=${left}`);
304 |
305 | const handleMessage = (event: MessageEvent) => {
306 | if (event.origin !== this.config.serverUrl) {
307 | return;
308 | }
309 |
310 | if (event.data.type === "windowClosed" && callback) {
311 | callback("login failed");
312 | }
313 |
314 | if (event.data.type === "loginSuccess") {
315 | this.signin(serverUrl, signinPath, event.data.data.code, event.data.data.state)
316 | .then((res: any) => {
317 | sessionStorage.setItem("token", res.token);
318 | window.location.reload();
319 | });
320 | popupWindow!.close();
321 | }
322 | };
323 |
324 | window.addEventListener("message", handleMessage);
325 | }
326 |
327 | public async signin_redirect(additionalParams?: IObject): Promise {
328 | window.location.assign(this.pkce.authorizeUrl(additionalParams));
329 | }
330 |
331 | public async exchangeForAccessToken(additionalParams?: IObject): Promise {
332 | return this.pkce.exchangeForAccessToken(window.location.href, additionalParams);
333 | }
334 |
335 | public async getUserInfo(accessToken: string): Promise {
336 | return fetch(`${this.config.serverUrl.trim()}/api/userinfo`, {
337 | method: "GET",
338 | headers: {
339 | "Authorization": `Bearer ${accessToken}`,
340 | "Content-Type": "application/json"
341 | },
342 | }).then(res => res.json()
343 | );
344 | }
345 |
346 | public parseAccessToken(accessToken: string): { header: JwtHeader, payload: JwtPayload } {
347 | try {
348 | const parsedHeader: JwtHeader = jwtDecode(accessToken, { header: true });
349 | const parsedPayload: JwtPayload = jwtDecode(accessToken);
350 | return { header: parsedHeader, payload: parsedPayload };
351 | } catch (error: any) {
352 | throw new Error(error.message);
353 | }
354 | }
355 |
356 | public refreshAccessToken(refreshToken: string): Promise {
357 | return this.pkce.refreshAccessToken(refreshToken);
358 | }
359 | }
360 |
361 | export default Sdk;
362 |
--------------------------------------------------------------------------------