Giter Club home page Giter Club logo

casdoor-nodejs-sdk's Introduction

casdoor-nodejs-sdk

GitHub Actions codebeat badge NPM version NPM download Release Discord

This is Casdoor's SDK for NodeJS will allow you to easily connect your application to the Casdoor authentication system without having to implement it from scratch.

Casdoor SDK is very simple to use. We will show you the steps below.

Examples

The following examples use Node.js Express as backend, but have different frontend frameworks. Choose the appropriate example based on your tech stack:

  1. React frontend: https://github.com/casdoor/casdoor-nodejs-react-example
  2. Angular frontend: https://github.com/casdoor/casdoor-nodejs-angular-example

Installation

# NPM
npm i casdoor-nodejs-sdk

# Yarn
yarn add casdoor-nodejs-sdk

Step1. Init SDK

Initialization requires 5 parameters, which are all string type:

Name (in order) Must Description
endpoint Yes Casdoor Server Url, such as http://localhost:8000
clientId Yes Client ID for the Casdoor application
clientSecret Yes Client secret for the Casdoor application
certificate Yes x509 certificate content of Application.cert
orgName Yes The name for the Casdoor organization
appName No The name for the Casdoor application
import { SDK, Config } from 'casdoor-nodejs-sdk'

const authCfg: Config = {
  endpoint: '',
  clientId: '',
  clientSecret: '',
  certificate: '',
  orgName: '',
}

const sdk = new SDK(authCfg)

// call sdk to handle

Step2. Get service and use

// user
const { data: users } = await sdk.getUsers()

// auth
const token = await sdk.getAuthToken('<callback-code>')
const user = sdk.parseJwtToken(token)

casdoor-nodejs-sdk's People

Contributors

dshilovprpl avatar fabian4 avatar gtn1024 avatar hsluoyz avatar huyonger avatar imchell avatar kusaljr avatar mogu4iy avatar nodece avatar nomeguy avatar palp1tate avatar qianxi0410 avatar selflocking avatar zhongjixiuxing avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

casdoor-nodejs-sdk's Issues

casdoor-nodejs-sdk there areconflicting or incompatible versions of dependencies specified

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: @typescript-eslint/[email protected]
npm ERR! node_modules/@typescript-eslint/parser
npm ERR! dev @typescript-eslint/parser@"^5.11.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @typescript-eslint/parser@"^4.0.0" from @typescript-eslint/[email protected]
npm ERR! node_modules/@typescript-eslint/eslint-plugin
npm ERR! dev @typescript-eslint/eslint-plugin@"^4.31.2" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR!
npm ERR! For a full report see:
npm ERR! C:\Users\samzh\AppData\Local\npm-cache_logs\2023-08-14T14_35_57_171Z-eresolve-report.txt

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\samzh\AppData\Local\npm-cache_logs\2023-08-14T14_35_57_171Z-debug-0.log

getToken parameter is inconsistent with api

SDK implementation code:

  public async getToken(id: string) {
    if (!this.request) {
      throw new Error('request init failed')
    }

    return (await this.request.get('/get-token', {
      params: {
        id: `admin/${id}`,  // Should admin be a username?
      },
    })) as unknown as Promise<AxiosResponse<{ data: Token }>>
  }

The api requires the id to be in the format owner/name:

// GetToken
// @Title GetToken
// @Tag Token API
// @Description get token
// @Param   id     query    string  true        "The id ( owner/name ) of token"
// @Success 200 {object} object.Token The Response object
// @router /get-token [get]
func (c *ApiController) GetToken() {
	id := c.Input().Get("id")
	token, err := object.GetToken(id)
	if err != nil {
		c.ResponseError(err.Error())
		return
	}

	c.ResponseOk(token)
}

If I pass built-in/admin, the api will throw an exception. If I pass admin, I can't get any data. What am I supposed to do?

Error While integrating sdk

exports.casdoorCallback = async function(req, res){
  var callbackUrl = new URL(`http://localhost:3000/${req.url}`);

  const authCfg = {
    issuer: config.casdoorAuthConfig.issuer,
    clientId: config.casdoorAuthConfig.clientId,
    clientSecret: config.casdoorAuthConfig.clientSecret,
  }
  
  const sdk = new SDK(authCfg)
  await sdk.init();

  const tokenSet = await sdk.callback({
    code: callbackUrl.searchParams.get('code'),
    state: callbackUrl.searchParams.get('state')
  })

  // const parseToken = sdk.parseJwtToken(tokenSet.access_token || '')

  // logger.info(parseToken)
  res.redirect('/')
}

This is the code which i wrote but on the block

const tokenSet = await sdk.callback({
    code: callbackUrl.searchParams.get('code'),
    state: callbackUrl.searchParams.get('state')
  })

It breaks and gives error

Started 2022-02-17T09:49:02.943Z GET /callback?code=345f7e569cd85f7eb2e4&state=forum ::1
node:internal/process/promises:265
            triggerUncaughtException(err, true /* fromPromise */);
            ^

[RequestError: connect ECONNREFUSED 127.0.0.1:443
  at ClientRequest.<anonymous> (/home/mayank/gsoc/nodeclub/node_modules/got/dist/source/core/index.js:962:111)
  at Object.onceWrapper (node:events:640:26)
  at ClientRequest.emit (node:events:532:35)
  at ClientRequest.origin.emit (/home/mayank/gsoc/nodeclub/node_modules/@szmarczak/http-timer/dist/source/index.js:43:20)
  at TLSSocket.socketErrorListener (node:_http_client:442:9)
  at TLSSocket.emit (node:events:520:28)
  at emitErrorNT (node:internal/streams/destroy:157:8)
  at emitErrorCloseNT (node:internal/streams/destroy:122:3)
  at processTicksAndRejections (node:internal/process/task_queues:83:21)
  at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1157:16)
] {
  code: 'ECONNREFUSED',
  timings: {
    start: 1645091343044,
    socket: 1645091343047,
    lookup: 1645091343048,
    connect: undefined,
    secureConnect: undefined,
    upload: undefined,
    response: undefined,
    end: undefined,
    error: 1645091343051,
    abort: undefined,
    phases: {
      wait: 3,
      dns: 1,
      tcp: undefined,
      tls: undefined,
      request: undefined,
      firstByte: undefined,
      download: undefined,
      total: 7
    }
  }
}

Which i can't figure out why it is happening

Question: "grant_type: is not supported in this application"

When I call sdk.getAuthToken(code) with Casdoor SaaS is always returning:

{
  "error": "unsupported_grant_type",
  "error_description": "grant_type:  is not supported in this application"
}

So I noticed is related to the Authorization headers, the SDK pass the client_id and client_secret as:
Authorization: Basic {base64}

But to work properly should pass as:
Authorization: Bearer Basic {base64}

Error getting authToken

I've following this example but when I change the serverUrl the request fail

app.post('*', (req, res) => {
  let urlObj = url.parse(req.url, true).query;
  sdk.getAuthToken(urlObj.code).then(response => {
    console.log(response)
    const accessToken = response.access_token;
    // const refresh_token = response.refresh_token;
    res.send(JSON.stringify({ token: accessToken }));
  });
});

https://github.com/casdoor/casdoor-nodejs-react-example/blob/b2293f0895a0e2817601faeafd593543d1c59314/backend/server.js#L88-L96

With the default application it is working fine (https://door.casdoor.com), however when I configure my server configuration, it still gives me the same error.
image
I think that behind the configuration, it never makes the request to the server, and it is always doing it to the casdoor url, as I put in the image
This is my server.js configuration

const authCfg = {
  endpoint: 'https://cas-door-api-g5262uil2a-uc.a.run.app',
  clientId: '7f527a08271d88e3aa80',
  clientSecret: 'ac042d287d923799441ab820327e30510c194be7',
  certificate: cert,
  orgName: 'acium-team',
  appName: 'application_5tusgq',

} and this is the settings.js configuration

  //serverUrl: "https://door.casdoor.com",
  serverUrl: 'https://cas-door-api-g5262uil2a-uc.a.run.app',
  clientId: "7f527a08271d88e3aa80",
  organizationName: "acium-team",
  appName: "application_5tusgq",
  /*clientId: "014ae4bd048734ca2dea",
  organizationName: "casbin",
  appName: "app-casnode",*/
  redirectPath: "/callback", // in accordance with casdoor configuration
};

_Originally posted by @ErnestoCamilo in https://github.com/casdoor/casdoor-nodejs-sdk/issues/40#issuecomment-1805775934_
            

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two Factor Authentication for your account, set its level to "Authorization only" in your account settings. semantic-release cannot publish with the default "
Authorization and writes" level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two Factor Authentication for your account, set its level to "Authorization only" in your account settings. semantic-release cannot publish with the default "
Authorization and writes" level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

[feature] How to get group tree with casdoor-nodejs-sdk?

The group tree means this part: https://door.casdoor.com/trees/built-in

image

The group tree mainly relies on the data returned by the get-groups API. But the returned data is a list. The Casdoor frontend code will build the tree from the list. We may need to do so too. There are two ways:

  1. Build the tree in Casdoor Go backend: https://github.com/casdoor/casdoor/blob/master/controllers/group.go#L31
  2. Build the tree in the SDK (like this casdoor-java-sdk)

image

casdoor-nodejs-sdk there are conflicting or incompatible versions of dependencies specified

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: @typescript-eslint/[email protected]
npm ERR! node_modules/@typescript-eslint/parser
npm ERR! dev @typescript-eslint/parser@"^5.11.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @typescript-eslint/parser@"^4.0.0" from @typescript-eslint/[email protected]
npm ERR! node_modules/@typescript-eslint/eslint-plugin
npm ERR! dev @typescript-eslint/eslint-plugin@"^4.31.2" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR!
npm ERR! For a full report see:
npm ERR! C:\Users\samzh\AppData\Local\npm-cache_logs\2023-08-14T13_26_36_992Z-eresolve-report.txt

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\samzh\AppData\Local\npm-cache_logs\2023-08-14T13_26_36_992Z-debug-0.log

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two Factor Authentication for your account, set its level to "Authorization only" in your account settings. semantic-release cannot publish with the default "
Authorization and writes" level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.