跳到主内容

Sign users in with a Casdoor SDK

This guide lists the Casdoor SDKs and explains how to sign users in to a web application with a frontend SDK and a backend SDK. The examples use casdoor-js-sdk and casdoor-go-sdk. The other SDKs follow the same steps.


Learning outcomes​

  • Choose the SDKs for your platform.
  • Configure the backend SDK and the frontend SDK.
  • Exchange the authorization code for an access token and verify the token.
  • Keep the user signed in to your application.
  • Manage users and applications through the SDK.

What you need​

  • A running Casdoor instance
  • An application in Casdoor, with the callback URL of your application in Redirect URLs
  • The client ID and client secret of the application, and the public key of its certificate

About the SDKs​

The Casdoor SDKs build on OpenID Connect (OIDC) and add functions of the Casdoor API, such as user management and file upload. They need a little more setup than a standard OIDC client and give you the full Casdoor API.

  • Frontend SDKs: For web frontends, mobile apps, and desktop apps. They build the sign-in URL and handle the callback in the UI.
  • Backend SDKs: For your server. They exchange the authorization code, verify tokens, and call the Casdoor API.

If your application has a separate frontend and backend, use a frontend SDK in the UI and a backend SDK on the server. For an example, see casdoor-python-vue-sdk-example. If your application renders pages on the server, as JSP and PHP applications do, a backend SDK alone can be enough.

Choose an SDK​

All official SDKs are in the casdoor organization on GitHub.

Web frontend SDKs​

Web前端SDK映射的工具SDK 代码示例代码
Javascript SDK对于传统的非SPA网站casdoor-js-sdkNode.js 后端:casdoor-raw-js-example
Go 后端:casdoor-go-react-sdk-example
仅前端的SDK仅用于前端的SPA网站casdoor-js-sdkcasdoor-react-only-example
React SDK适用于React网站casdoor-react-sdkNode.js 后端:casdoor-nodejs-react-example
Java 后端:casdoor-spring-security-react-example
Next.js SDK针对Next.js网站nextjs-auth
Nuxt SDK对于Nuxt网站nuxt-auth
Vue SDK适用于Vue网站casdoor-vue-sdkcasdoor-python-vue-sdk-example
Angular SDK适用于Angular网站casdoor-angular-sdkcasdoor-nodejs-angular-example
Flutter SDK适用于Flutter Web网站casdoor-flutter-sdkcasdoor-flutter-example
ASP.NET SDK适用于ASP.NET Blazor WASM网站Blazor.BFF.OpenIDConnect.Templatecasdoor-dotnet-blazorwasm-oidc-example
Firebase SDK适用于 Google Firebase 应用casdoor-firebase-example

Web backend SDKs​

Web后端SDK描述Sdk 代码示例代码
Go SDK对于Go后端casdoor-go-sdkcasdoor-go-react-sdk-example
Java SDK针对Java后端casdoor-java-sdkcasdoor-spring-boot-starter, casdoor-spring-boot-example, casdoor-spring-security-react-example, quarkus-casdoor-auth (Quarkus)
Node.js SDK针对Node.js后端casdoor-nodejs-sdkcasdoor-nodejs-react-example
Python SDK针对Python后端casdoor-python-sdkFlask:casdoor-python-vue-sdk-example
Django:casdoor-django-js-sdk-example
FastAPI:casdoor-fastapi-js-sdk-example
PHP SDK针对PHP后端casdoor-php-sdkwordpress-casdoor-plugin
.NET SDK针对ASP.NET后端casdoor-dotnet-sdkcasdoor-dotnet-sdk-example
Rust SDK针对Rust后端casdoor-rust-sdkcasdoor-rust-example
C/C++ SDK针对 C/C++ 后端casdoor-cpp-sdkcasdoor-cpp-qt-example
Dart SDK针对Dart后端casdoor-dart-sdk
Ruby SDK针对Ruby后端casdoor-ruby-sdk

Mobile SDKs​

移动SDK描述SDK 代码示例代码
Android SDK适用于Android应用casdoor-android-sdkcasdoor-android-example
iOS SDK针对iOS应用程序casdoor-ios-sdkcasdoor-ios-example
React Native SDK对于React Native应用程序casdoor-react-native-sdkcasdoor-react-native-example
Flutter SDK适用于Flutter应用casdoor-flutter-sdkcasdoor-flutter-example
Firebase SDK适用于 Google Firebase 应用casdoor-firebase-example
Unity游戏SDK适用于Unity 2D/3D PC/移动游戏casdoor-dotnet-sdkcasdoor-unity-example
uni-app SDK对于uni-app应用程序casdoor-uniapp-sdkcasdoor-uniapp-example
提示

A mobile app that signs users in natively, without a browser, can use the verification code grant for sign-in by SMS or email with automatic sign-up. Signed-in users can also approve the QR code on the sign-in page of your website from the app.

Desktop SDKs​

桌面版SDK描述SDK 代码示例代码
Electron SDK对于Electron应用casdoor-js-sdkcasdoor-electron-example
.NET 桌面 SDK适用于 .NET 桌面应用casdoor-dotnet-sdkWPF:casdoor-dotnet-desktop-example
WinForms:casdoor-dotnet-winform-example
Avalonia UI:casdoor-dotnet-avalonia-example
C/C++ SDK用于C/C++桌面应用程序casdoor-cpp-sdkcasdoor-cpp-qt-example

Configure the backend SDK​

When your backend starts, initialize the SDK with the address of Casdoor and the credentials of the application. With casdoor-go-sdk:

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)
}

InitConfig() takes the following parameters:

参数必须描述
endpoint是Casdoor 服务器地址,例如 https://door.casdoor.com 或 http://localhost:8000
clientId是Casdoor应用的客户端ID
clientSecret是Casdoor应用程序的客户端密钥
jwtPublicKey是Casdoor应用程序的证书的公钥
organizationName是Casdoor组织的名称
应用程序名称不Casdoor应用程序的名称

To get the value of jwtPublicKey:

  1. In the Casdoor admin console, open the Certs page.

    Certs page with the list of certificates

  2. Open the certificate and copy or download its public key.

    Certificate edit page with the public key

  3. On the edit page of the application, select the same certificate in Cert.

    Application edit page with the certificate selected

Configure the frontend SDK​

  1. Install casdoor-js-sdk with npm:

    npm install casdoor-js-sdk

    Or with Yarn:

    yarn add casdoor-js-sdk
  2. Define helper functions in a shared file, such as 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;
    }
  3. In the entry file of the frontend, such as index.js or app.js in React, initialize the SDK. Use the same values for the first four settings as in the backend SDK. redirectPath is the path of your application that Casdoor sends the user back to after sign-in.

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

    xxx.initCasdoorSdk(config);
  4. Handle the callback route. In this React example, a component handles /callback and forwards the code to the backend. Skip this step if Casdoor redirects straight to your backend, as in JSP and PHP applications.

    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);

Give users a Sign in and a Sign up button or link. Get the URLs from the frontend SDK or the backend SDK. See Sign-in and sign-up URLs.

Get and verify the access token​

The sign-in flow has three steps:

  1. The user clicks the sign-in link and arrives at the Casdoor sign-in page, for example:

    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 a username and password and clicks Sign In, or clicks the button of a provider, such as the GitHub button.

  3. Casdoor redirects the user to your application with an authorization code, for example https://forum.casbin.com?code=xxx&state=yyy.

Your backend then exchanges the code for an access token with GetOAuthToken() and verifies the token with ParseJwtToken():

// 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() returns no error, the token is valid and Casdoor issued it. The user is signed in. Use the returned claims to identify the user. For a complete example, see the sign-in handler of Casnode, a forum written in Go.

Keep the user signed in​

How your application remembers the user is your own design decision and not part of OIDC, OAuth 2.0, or Casdoor. This section describes two common ways.

The claims that ParseJwtToken() returns have the following type:

type Claims struct {
User
AccessToken string `json:"accessToken"`
jwt.RegisteredClaims
}
FieldDescription
UserThe user, with all profile fields. See User
AccessTokenThe access token string
jwt.RegisteredClaimsThe standard claims of a JSON Web Token (JWT)

In Casdoor, the access token usually has the same content as the ID token, so it carries the information about the signed-in user.

Use a server-side session​

Store the claims in the session of your web framework. How you do that depends on the language and the framework. Casnode uses the Beego framework and stores the user with 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

Use the access token as a JWT​

The access token is a JWT. If your application keeps sessions in JWTs, use the access token directly:

  1. Send the access token to the frontend and store it there, for example in the localStorage of the browser.
  2. Send the access token to the backend with every request.
  3. In the backend, verify the token with ParseJwtToken() or your own function, and read the signed-in user from it.

Manage users through the SDK​

The backend SDKs wrap the Casdoor API. This part is not OIDC or OAuth 2.0. The functions include:

FunctionDescription
GetUser(name string)Gets a user by username
GetUsers()Gets all users
AddUser()Adds a user
UpdateUser()Updates a user
DeleteUser()Deletes a user
CheckUserPassword(auth.User)Checks the password of a user

If the SDK has no function for an endpoint, call the Casdoor API directly.

Manage applications through the SDK​

FunctionDescription
AddApplication()Creates an application
GetApplication(name string)Gets an application by name
GetApplications()Gets all applications
UpdateApplication()Updates an application
DeleteApplication()Deletes an application

When you create an application with AddApplication(), Casdoor fills in the default sign-up items (ID, Username, Display name, Password, Confirm password, Email, Phone, Agreement), sign-in items, and sign-in methods. The application works in the UI without further configuration.

See also​