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
| SDK для веб-фронтенду | Опис | Код SDK | Приклад коду |
|---|---|---|---|
| Javascript SDK | Для традиційних не-SPA веб-сайтів | casdoor-js-sdk | Nodejs backend: casdoor-raw-js-example Go backend: casdoor-go-react-sdk-example |
| SDK лише для фронтенду | Для веб-сайтів SPA лише з фронтендом | casdoor-js-sdk | casdoor-react-only-example |
| React SDK | Для веб-сайтів на React | casdoor-react-sdk | Nodejs backend: casdoor-nodejs-react-example Java backend: casdoor-spring-security-react-example |
| Next.js SDK | Для веб-сайтів на Next.js | nextjs-auth | |
| Nuxt SDK | Для веб-сайтів на Nuxt | nuxt-auth | |
| Vue SDK | For Vue websites | casdoor-vue-sdk | casdoor-python-vue-sdk-example |
| Angular SDK | For Angular websites | casdoor-angular-sdk | casdoor-nodejs-angular-example |
| Flutter SDK | For Flutter Web websites | casdoor-flutter-sdk | casdoor-flutter-example |
| ASP.NET SDK | For ASP.NET Blazor WASM websites | Blazor.BFF.OpenIDConnect.Template | casdoor-dotnet-blazorwasm-oidc-example |
| Firebase SDK | Для додатків Google Firebase | casdoor-firebase-example |
Web backend SDKs
| SDK для веб-бекенду | Опис | Код Sdk | Приклад коду |
|---|---|---|---|
| Go SDK | Для Go бекендів | casdoor-go-sdk | casdoor-go-react-sdk-example |
| Java SDK | Для Java бекендів | casdoor-java-sdk | casdoor-spring-boot-starter, casdoor-spring-boot-example, casdoor-spring-security-react-example, quarkus-casdoor-auth (Quarkus) |
| Node.js SDK | Для Node.js бекендів | casdoor-nodejs-sdk | casdoor-nodejs-react-example |
| Python SDK | Для Python бекендів | casdoor-python-sdk | Flask: casdoor-python-vue-sdk-example Django: casdoor-django-js-sdk-example FastAPI: casdoor-fastapi-js-sdk-example |
| PHP SDK | Для PHP бекендів | casdoor-php-sdk | wordpress-casdoor-plugin |
| .NET SDK | Для ASP.NET бекендів | casdoor-dotnet-sdk | casdoor-dotnet-sdk-example |
| Rust SDK | Для Rust бекендів | casdoor-rust-sdk | casdoor-rust-example |
| C/C++ SDK | Для C/C++ бекендів | casdoor-cpp-sdk | casdoor-cpp-qt-example |
| Dart SDK | Для Dart бекендів | casdoor-dart-sdk | |
| Ruby SDK | Для Ruby бекендів | casdoor-ruby-sdk |
Mobile SDKs
| Mobile SDK | Опис | Код SDK | Приклад коду |
|---|---|---|---|
| Android SDK | Для Android додатків | casdoor-android-sdk | casdoor-android-example |
| iOS SDK | Для iOS додатків | casdoor-ios-sdk | casdoor-ios-example |
| React Native SDK | Для дода тків React Native | casdoor-react-native-sdk | casdoor-react-native-example |
| Flutter SDK | Для Flutter додатків | casdoor-flutter-sdk | casdoor-flutter-example |
| Firebase SDK | Для додатків Google Firebase | casdoor-firebase-example | |
| Unity Games SDK | Для 2D/3D ігор на Unity для ПК/мобільних пристроїв | casdoor-dotnet-sdk | casdoor-unity-example |
| uni-app SDK | Для додатків uni-app | casdoor-uniapp-sdk | casdoor-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 | Приклад коду |
|---|---|---|---|
| Electron SDK | Для додатків Electron | casdoor-js-sdk | casdoor-electron-example |
| .NET SDK для робочого столу | Для .NET додатків для робочого столу | casdoor-dotnet-sdk | WPF: casdoor-dotnet-desktop-example WinForms: casdoor-dotnet-winform-example Avalonia UI: casdoor-dotnet-avalonia-example |
| C/C++ SDK | Для C/C++ додатків для робочого столу | casdoor-cpp-sdk | casdoor-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 Server URL, like https://door.casdoor.com or http://localhost:8000 |
| clientId | Так | Client ID для додатку Casdoor |
| clientSecret | Так | Client secret для додатку Casdoor |
| jwtPublicKey | Так | Публічний ключ для сертифіката додатку Casdoor |
| organizationName | Так | Назва для організації Casdoor |
| applicationName | Ні | Назва для додатку Casdoor |
To get the value of jwtPublicKey:
-
In the Casdoor admin console, open the Certs page.

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

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

Configure the frontend SDK
-
Install
casdoor-js-sdkwith npm:npm install casdoor-js-sdkOr with Yarn:
yarn add casdoor-js-sdk -
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;
} -
In the entry file of the frontend, such as
index.jsorapp.jsin React, initialize the SDK. Use the same values for the first four settings as in the backend SDK.redirectPathis 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); -
Handle the callback route. In this React example, a component handles
/callbackand 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);
Show the sign-in and sign-up links
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:
-
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 -
The user enters a username and password and clicks Sign In, or clicks the button of a provider, such as the GitHub button.
-
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
}
| Field | Description |
|---|---|
User | The user, with all profile fields. See User |
AccessToken | The access token string |
jwt.RegisteredClaims | The 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:
- Send the access token to the frontend and store it there, for example in the
localStorageof the browser. - Send the access token to the backend with every request.
- 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:
| Function | Description |
|---|---|
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
| Function | Description |
|---|---|
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.