Zum Hauptinhalt springen

Casdoor SDKs

Übersicht​

Casdoor SDKs extend standard OIDC with user management, resource uploads, and other features. They take a bit more setup than a generic OIDC client but give you the full Casdoor API.

Frontend SDKs — For web (JavaScript, React, Vue, etc.) and mobile (Android, iOS, React Native, Flutter).
Backend SDKs — For Go, Java, Node.js, Python, PHP, .NET, Rust, C++, and more.

Tipp

For a frontend/backend split, use a frontend SDK (e.g. casdoor-js-sdk, casdoor-react-sdk, casdoor-vue-sdk) in the UI and a backend SDK for token validation and API calls. For a traditional server-rendered app (JSP, PHP), a backend SDK may be enough. Example: casdoor-python-vue-sdk-example.

Mobile SDKBeschreibungSDK-CodeBeispielcode
Android SDKFür Android-Appscasdoor-android-sdkcasdoor-android-example
iOS SDKFür iOS-Appscasdoor-ios-sdkcasdoor-ios-example
React Native SDKFür React Native-Appscasdoor-react-native-sdkcasdoor-react-native-example
Flutter SDKFür Flutter-Appscasdoor-flutter-sdkcasdoor-flutter-example
Firebase SDKFür Google Firebase-Appscasdoor-firebase-example
Unity Games SDKFür Unity 2D/3D PC/Mobile-Spielecasdoor-dotnet-sdkcasdoor-unity-example
uni-app SDKFür uni-app-Appscasdoor-uniapp-sdkcasdoor-uniapp-example
Desktop SDKBeschreibungSDK-CodeBeispielcode
Electron SDKFür Electron-Appscasdoor-js-sdkcasdoor-electron-example
.NET Desktop SDKFür .NET-Desktop-Appscasdoor-dotnet-sdkWPF: casdoor-dotnet-desktop-example
WinForms: casdoor-dotnet-winform-example
Avalonia UI: casdoor-dotnet-avalonia-example
C/C++ SDKFür C/C++-Desktop-Appscasdoor-cpp-sdkcasdoor-cpp-qt-example
Web-Frontend-SDKBeschreibungSDK-CodeBeispielcode
Javascript SDKFür traditionelle Nicht-SPA-Websitescasdoor-js-sdkNodejs backend: casdoor-raw-js-example
Go backend: casdoor-go-react-sdk-example
Frontend-only SDKFür Frontend-only-SPA-Websitescasdoor-js-sdkcasdoor-react-only-example
React SDKFür React-Websitescasdoor-react-sdkNodejs backend: casdoor-nodejs-react-example
Java backend: casdoor-spring-security-react-example
Next.js SDKFür Next.js-Websitesnextjs-auth
Nuxt SDKFür Nuxt-Websitesnuxt-auth
Vue SDKFor Vue websitescasdoor-vue-sdkcasdoor-python-vue-sdk-example
Angular SDKFor Angular websitescasdoor-angular-sdkcasdoor-nodejs-angular-example
Flutter SDKFor Flutter Web websitescasdoor-flutter-sdkcasdoor-flutter-example
ASP.NET SDKFor ASP.NET Blazor WASM websitesBlazor.BFF.OpenIDConnect.Templatecasdoor-dotnet-blazorwasm-oidc-example
Firebase SDKFür Google Firebase-Appscasdoor-firebase-example

Pair the frontend with a backend SDK in your server’s language:

Web-Backend-SDKBeschreibungSDK-CodeBeispielcode
Go SDKFür Go-Backendscasdoor-go-sdkcasdoor-go-react-sdk-example
Java SDKFür Java-Backendscasdoor-java-sdkcasdoor-spring-boot-starter, casdoor-spring-boot-example, casdoor-spring-security-react-example
Node.js SDKFür Node.js-Backendscasdoor-nodejs-sdkcasdoor-nodejs-react-example
Python SDKFür Python-Backendscasdoor-python-sdkFlask: casdoor-python-vue-sdk-example
Django: casdoor-django-js-sdk-example
FastAPI: casdoor-fastapi-js-sdk-example
PHP SDKFür PHP-Backendscasdoor-php-sdkwordpress-casdoor-plugin
.NET SDKFür ASP.NET-Backendscasdoor-dotnet-sdkcasdoor-dotnet-sdk-example
Rust SDKFür Rust-Backendscasdoor-rust-sdkcasdoor-rust-example
C/C++ SDKFür C/C++-Backendscasdoor-cpp-sdkcasdoor-cpp-qt-example
Dart SDKFür Dart-Backendscasdoor-dart-sdk
Ruby SDKFür Ruby-Backendscasdoor-ruby-sdk

All official SDKs: https://github.com/orgs/casdoor/repositories?q=sdk&type=all&language=&sort=.

Using the SDK​

1. Backend SDK-Konfiguration​

On startup, call the SDK’s init function with your Casdoor endpoint, client ID, client secret, and (for JWT validation) the public key. Example with casdoor-go-sdk: https://github.com/casbin/casnode/blob/6d4c55f5c9a3c4bd8c85f2493abad3553b9c7ac0/controllers/account.go#L51-L64

var CasdoorEndpoint = "https://door.casdoor.com"
var ClientId = "541738959670d221d59d"
var ClientSecret = "66863369a64a5863827cf949bab70ed560ba24bf"
var CasdoorOrganization = "casbin"
var CasdoorApplication = "app-casnode"

//go:embed token_jwt_key.pem
var JwtPublicKey string

func init() {
auth.InitConfig(CasdoorEndpoint, ClientId, ClientSecret, JwtPublicKey, CasdoorOrganization, CasdoorApplication)
}

All the parameters for InitConfig() are explained as follows:

KonfigurationsparameterMussBeschreibung
EndpunktJaCasdoor Server URL, like https://door.casdoor.com or http://localhost:8000
clientIdJaClient-ID für die Casdoor-Anwendung
clientSecretJaClient-Geheimnis für die Casdoor-Anwendung
jwtPublicKeyJaDer öffentliche Schlüssel für das Zertifikat der Casdoor-Anwendung
organizationNameJaDer Name für die Casdoor-Organisation
applicationNameNeinDer Name für die Casdoor-Anwendung
Tipp

The jwtPublicKey can be managed in the Certs page as below.

Certs Management

Copy or download the public key from the certificate edit page for use in the SDK.

Certs Edit

Then select the cert on the application edit page.

Certs Select

2. Frontend-Konfiguration​

Zuerst installieren Sie casdoor-js-sdk über NPM oder Yarn:

npm install casdoor-js-sdk

Oder:

yarn add casdoor-js-sdk

Then define the following utility functions (better in a global JS file like Setting.js):

import Sdk from "casdoor-js-sdk";

export function initCasdoorSdk(config) {
CasdoorSdk = new Sdk(config);
}

export function getSignupUrl() {
return CasdoorSdk.getSignupUrl();
}

export function getSigninUrl() {
return CasdoorSdk.getSigninUrl();
}

export function getUserProfileUrl(userName, account) {
return CasdoorSdk.getUserProfileUrl(userName, account);
}

export function getMyProfileUrl(account) {
return CasdoorSdk.getMyProfileUrl(account);
}

export function getMyResourcesUrl(account) {
return CasdoorSdk.getMyProfileUrl(account).replace("/account?", "/resources?");
}

export function signin() {
return CasdoorSdk.signin(ServerUrl);
}

export function showMessage(type, text) {
if (type === "") {
return;
} else if (type === "success") {
message.success(text);
} else if (type === "error") {
message.error(text);
}
}

export function goToLink(link) {
window.location.href = link;
}

In your frontend entry file (e.g. index.js or app.js in React), initialize the casdoor-js-sdk by calling InitConfig() with the required parameters. Die ersten 4 Parameter sollten denselben Wert wie das Casdoor Backend SDK verwenden. The last parameter redirectPath is relative path for the redirected URL, returned from Casdoor's login page.

const config = {
serverUrl: "https://door.casdoor.com",
clientId: "014ae4bd048734ca2dea",
organizationName: "casbin",
appName: "app-casnode",
redirectPath: "/callback",
};

xxx.initCasdoorSdk(config);

(Optional) This example uses React; the /callback route is handled by the component below, which forwards the call to the backend. Skip this if your callback goes directly to the backend (e.g. JSP or PHP).

import React from "react";
import {Button, Result, Spin} from "antd";
import {withRouter} from "react-router-dom";
import * as Setting from "./Setting";

class AuthCallback extends React.Component {
constructor(props) {
super(props);
this.state = {
classes: props,
msg: null,
};
}

componentWillMount() {
this.login();
}

login() {
Setting.signin().then((res) => {
if (res.status === "ok") {
Setting.showMessage("success", `Logged in successfully`);
Setting.goToLink("/");
} else {
this.setState({
msg: res.msg,
});
}
});
}

render() {
return (
<div style={{textAlign: "center"}}>
{this.state.msg === null ? (
<Spin
size="large"
tip="Signing in..."
style={{paddingTop: "10%"}}
/>
) : (
<div style={{display: "inline"}}>
<Result
status="error"
title="Login Error"
subTitle={this.state.msg}
extra={[
<Button type="primary" key="details">
Details
</Button>,
<Button key="help">Help</Button>,
]}
/>
</div>
)}
</div>
);
}
}

export default withRouter(AuthCallback);

3. Login-URLs erhalten​

Show "Sign up" and "Sign in" buttons or links to users; URLs can be obtained from the frontend or backend. See Login URLs.

4. Zugriffstoken abrufen und überprüfen​

Hier sind die Schritte:

  1. The user clicks the login URL and is redirected to Casdoor's login page, like: https://door.casdoor.com/login/oauth/authorize?client_id=014ae4bd048734ca2dea&response_type=code&redirect_uri=https%3A%2F%2Fforum.casbin.com%2Fcallback&scope=read&state=app-casnode
  2. The user enters username & password and clicks Sign In (or just click the third-party login button like Sign in with GitHub).
  3. The user is redirected back to your application with the authorization code issued by Casdoor ( like: https://forum.casbin.com?code=xxx&state=yyy), your application's backend needs to exchange the authorization code with the access token and verify that the access token is valid and issued by Casdoor. The functions GetOAuthToken() and ParseJwtToken() are provided by Casdoor backend SDK.

Der folgende Code zeigt, wie man das Zugriffstoken abruft und überprüft. For a real example of Casnode (a forum website written in Go), see: https://github.com/casbin/casnode/blob/6d4c55f5c9a3c4bd8c85f2493abad3553b9c7ac0/controllers/account.go#L51-L64

// get code and state from the GET parameters of the redirected URL
code := c.Input().Get("code")
state := c.Input().Get("state")

// exchange the access token with code and state
token, err := auth.GetOAuthToken(code, state)
if err != nil {
panic(err)
}

// verify the access token
claims, err := auth.ParseJwtToken(token.AccessToken)
if err != nil {
panic(err)
}

If ParseJwtToken() finishes with no error, then the user has successfully logged into the application. The returned claims can be used to identity the user later.

4. Benutzer mit Zugriffstoken identifizieren​

Info

Dieser Teil ist eigentlich die eigene Geschäftslogik Ihrer Anwendung und nicht Teil von OIDC, OAuth oder Casdoor. Wir bieten nur bewährte Praktiken, da viele Leute nicht wissen, was sie als nächsten Schritt tun sollen.

In Casdoor ist das Zugriffstoken normalerweise identisch mit dem ID-Token. Sie sind dasselbe. Also enthält das Zugriffstoken alle Informationen für den eingeloggten Benutzer.

The variable claims returned by ParseJwtToken() is defined as:

type Claims struct {
User
AccessToken string `json:"accessToken"`
jwt.RegisteredClaims
}
  1. User: the User object, containing all information for the logged-in user, see definition at: /docs/basic/core-concepts#user
  2. AccessToken: the access token string.
  3. jwt.RegisteredClaims: some other values required by JWT.

At this moment, the application usually has two ways to remember the user session: session and JWT.

Session​

Die Methode zum Setzen der Sitzung variiert stark je nach Sprache und Web-Framework. E.g., Casnode uses Beego web framework and set session by calling: c.SetSessionUser().

token, err := auth.GetOAuthToken(code, state)
if err != nil {
panic(err)
}

claims, err := auth.ParseJwtToken(token.AccessToken)
if err != nil {
panic(err)
}

claims.AccessToken = token.AccessToken
c.SetSessionUser(claims) // set session

JWT​

The accessToken returned by Casdoor is actually a JWT. Wenn Ihre Anwendung JWT verwendet, um die Benutzersitzung zu halten, verwenden Sie einfach das Zugriffstoken direkt dafür:

  1. Senden Sie das Zugriffstoken an das Frontend, speichern Sie es an Orten wie dem localStorage des Browsers.
  2. Lassen Sie den Browser das Zugriffstoken für jede Anfrage an das Backend senden.
  3. Call ParseJwtToken() or your own function to verify the access token and get logged-in user information in your backend.

5. (Optional) Interact with the User table​

Info

This part is provided by Casdoor Public API and not part of the OIDC or OAuth.

Casdoor Backend SDK bietet viele Hilfsfunktionen, nicht nur beschränkt auf:

  • GetUser(name string): get a user by username.
  • GetUsers(): get all users.
  • AddUser(): add a user.
  • UpdateUser(): update a user.
  • DeleteUser(): delete a user.
  • CheckUserPassword(auth.User): check user's password.

These functions are implemented by making RESTful calls against Casdoor Public API. If a function is not in the Casdoor Backend SDK, call the Public API directly.

6. (Optional) Manage Applications via SDK​

Casdoor SDKs also provide functions to manage applications programmatically:

  • AddApplication(): create a new application.
  • GetApplication(name string): get an application by name.
  • GetApplications(): get all applications.
  • UpdateApplication(): update an application.
  • DeleteApplication(): delete an application.

When creating applications via SDK using AddApplication(), Casdoor automatically initializes essential fields with sensible defaults. This includes signup items (ID, Username, Display name, Password, Confirm password, Email, Phone, Agreement), signin items, and signin methods. This ensures applications created programmatically work correctly in the UI without requiring manual configuration of these basic settings.