Skip to main content

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 frontend SDKDescriptionSDK codeExample code
Javascript SDKFor traditional non-SPA websitescasdoor-js-sdkNodejs backend: casdoor-raw-js-example
Go backend: casdoor-go-react-sdk-example
Frontend-only SDKFor frontend-only SPA websitescasdoor-js-sdkcasdoor-react-only-example
React SDKFor React websitescasdoor-react-sdkNodejs backend: casdoor-nodejs-react-example
Java backend: casdoor-spring-security-react-example
Next.js SDKFor Next.js websitesnextjs-auth
Nuxt SDKFor 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 SDKFor Google Firebase appscasdoor-firebase-example

Web backend SDKs​

Web backend SDKDescriptionSdk codeExample code
Go SDKFor Go backendscasdoor-go-sdkcasdoor-go-react-sdk-example
Java SDKFor Java backendscasdoor-java-sdkcasdoor-spring-boot-starter, casdoor-spring-boot-example, casdoor-spring-security-react-example, quarkus-casdoor-auth (Quarkus)
Node.js SDKFor Node.js backendscasdoor-nodejs-sdkcasdoor-nodejs-react-example
Python SDKFor Python backendscasdoor-python-sdkFlask: casdoor-python-vue-sdk-example
Django: casdoor-django-js-sdk-example
FastAPI: casdoor-fastapi-js-sdk-example
PHP SDKFor PHP backendscasdoor-php-sdkwordpress-casdoor-plugin
.NET SDKFor ASP.NET backendscasdoor-dotnet-sdkcasdoor-dotnet-sdk-example
Rust SDKFor Rust backendscasdoor-rust-sdkcasdoor-rust-example
C/C++ SDKFor C/C++ backendscasdoor-cpp-sdkcasdoor-cpp-qt-example
Dart SDKFor Dart backendscasdoor-dart-sdk
Ruby SDKFor Ruby backendscasdoor-ruby-sdk

Mobile SDKs​

Mobile SDKDescriptionSDK codeExample code
Android SDKFor Android appscasdoor-android-sdkcasdoor-android-example
iOS SDKFor iOS appscasdoor-ios-sdkcasdoor-ios-example
React Native SDKFor React Native appscasdoor-react-native-sdkcasdoor-react-native-example
Flutter SDKFor Flutter appscasdoor-flutter-sdkcasdoor-flutter-example
Firebase SDKFor Google Firebase appscasdoor-firebase-example
Unity Games SDKFor Unity 2D/3D PC/Mobile gamescasdoor-dotnet-sdkcasdoor-unity-example
uni-app SDKFor uni-app appscasdoor-uniapp-sdkcasdoor-uniapp-example
tip

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​

Desktop SDKDescriptionSDK codeExample code
Electron SDKFor Electron appscasdoor-js-sdkcasdoor-electron-example
.NET Desktop SDKFor .NET desktop appscasdoor-dotnet-sdkWPF: casdoor-dotnet-desktop-example
WinForms: casdoor-dotnet-winform-example
Avalonia UI: casdoor-dotnet-avalonia-example
C/C++ SDKFor C/C++ desktop appscasdoor-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:

ParameterMustDescription
endpointYesCasdoor Server URL, like https://door.casdoor.com or http://localhost:8000
clientIdYesClient ID for the Casdoor application
clientSecretYesClient secret for the Casdoor application
jwtPublicKeyYesThe public key for the Casdoor application's cert
organizationNameYesThe name for the Casdoor organization
applicationNameNoThe name for the Casdoor application

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​