Hanzo
PlatformHanzo IAMConnecting to IAM

Hanzo IAM SDKs

Use Hanzo IAM SDKs for frontend and backend integration with user management and more.

Overview

Hanzo IAM 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 Hanzo IAM 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.

:::tip For a frontend/backend split, use a frontend SDK (e.g. iam-js-sdk, iam-react-sdk, iam-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: iam-python-vue-sdk-example. :::

Mobile SDKDescriptionSDK codeExample code
Android SDKFor Android appsiam-android-sdkiam-android-example
iOS SDKFor iOS appsiam-ios-sdkiam-ios-example
React Native SDKFor React Native appsiam-react-native-sdkiam-react-native-example
Flutter SDKFor Flutter appsiam-flutter-sdkiam-flutter-example
Firebase SDKFor Google Firebase appsiam-firebase-example
Unity Games SDKFor Unity 2D/3D PC/Mobile gamesiam-dotnet-sdkiam-unity-example
uni-app SDKFor uni-app appsiam-uniapp-sdkiam-uniapp-example
Desktop SDKDescriptionSDK codeExample code
Electron SDKFor Electron appsiam-js-sdkiam-electron-example
.NET Desktop SDKFor .NET desktop appsiam-dotnet-sdkWPF: iam-dotnet-desktop-example
WinForms: iam-dotnet-winform-example
Avalonia UI: iam-dotnet-avalonia-example
C/C++ SDKFor C/C++ desktop appsiam-cpp-sdkiam-cpp-qt-example
Web frontend SDKDescriptionSDK codeExample code
Javascript SDKFor traditional non-SPA websitesiam-js-sdkNodejs backend: iam-raw-js-example
Go backend: iam-go-react-sdk-example
Frontend-only SDKFor frontend-only SPA websitesiam-js-sdkiam-react-only-example
React SDKFor React websitesiam-react-sdkNodejs backend: iam-nodejs-react-example
Java backend: iam-spring-security-react-example
Next.js SDKFor Next.js websitesnextjs-auth
Nuxt SDKFor Nuxt websitesnuxt-auth
Vue SDKFor Vue websitesiam-vue-sdkiam-python-vue-sdk-example
Angular SDKFor Angular websitesiam-angular-sdkiam-nodejs-angular-example
Flutter SDKFor Flutter Web websitesiam-flutter-sdkiam-flutter-example
ASP.NET SDKFor ASP.NET Blazor WASM websitesBlazor.BFF.OpenIDConnect.Templateiam-dotnet-blazorwasm-oidc-example
Firebase SDKFor Google Firebase appsiam-firebase-example

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

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

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

Using the SDK

Backend SDK configuration

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

var Hanzo IAMEndpoint = "https://iam.hanzo.ai"
var ClientId = "541738959670d221d59d"
var ClientSecret = "66863369a64a5863827cf949bab70ed560ba24bf"
var Hanzo IAMOrganization = "casbin"
var Hanzo IAMApplication = "app-casnode"

//go:embed token_jwt_key.pem
var JwtPublicKey string

func init() {
    auth.InitConfig(Hanzo IAMEndpoint, ClientId, ClientSecret, JwtPublicKey, Hanzo IAMOrganization, Hanzo IAMApplication)
}

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

| Parameter        | Must | Description                                                                    |
|------------------|------|--------------------------------------------------------------------------------|
| endpoint         | Yes  | Hanzo IAM Server URL, like `https://iam.hanzo.ai` or `http://localhost:8000` |
| clientId         | Yes  | Client ID for the Hanzo IAM application                                          |
| clientSecret     | Yes  | Client secret for the Hanzo IAM application                                      |
| jwtPublicKey     | Yes  | The public key for the Hanzo IAM application's cert                              |
| organizationName | Yes  | The name for the Hanzo IAM organization                                          |
| applicationName  | No   | The name for the Hanzo IAM application                                           |

:::tip

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

![Certs Management](/img/how-to-connect/sdk/howto_cert_list.png)

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

![Certs Edit](/img/how-to-connect/sdk/howto_cert_edit.png)

Then select the cert on the application edit page.

![Certs Select](/img/how-to-connect/sdk/howto_cert_select.png)

:::

### 2. Frontend configuration

First, install `iam-js-sdk` via NPM or Yarn:

```shell
npm install iam-js-sdk

Or:

```shell
yarn add iam-js-sdk

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

```js
import Sdk from "iam-js-sdk";

export function initHanzo IAMSdk(config) {
  Hanzo IAMSdk = new Sdk(config);
}

export function getSignupUrl() {
  return Hanzo IAMSdk.getSignupUrl();
}

export function getSigninUrl() {
  return Hanzo IAMSdk.getSigninUrl();
}

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

export function getMyProfileUrl(account) {
  return Hanzo IAMSdk.getMyProfileUrl(account);
}

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

export function signin() {
  return Hanzo IAMSdk.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 `iam-js-sdk` by calling `InitConfig()` with the required parameters. The first 4 parameters should use the same value as the Hanzo IAM backend SDK. The last parameter `redirectPath` is relative path for the redirected URL, returned from Hanzo IAM's login page.

```js
const config = {
  serverUrl: "https://iam.hanzo.ai",
  clientId: "014ae4bd048734ca2dea",
  organizationName: "casbin",
  appName: "app-casnode",
  redirectPath: "/callback",
};

xxx.initHanzo IAMSdk(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).

```js
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. Get login URLs

Show "Sign up" and "Sign in" buttons or links to users; URLs can be obtained from the frontend or backend. See [Login URLs](/docs/basic/core-concepts#login-urls).

### 4. Get and verify access token

Here are the steps:

1. The user clicks the login URL and is redirected to Hanzo IAM's login page,
   like: `https://iam.hanzo.ai/oauth/authorize?client_id=014ae4bd048734ca2dea&response_type=code&redirect_uri=https%3A%2F%2Fgithub.com/hanzoai/iam%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 Hanzo IAM (
   like: `https://github.com/hanzoai/iam?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 Hanzo IAM. The functions `GetOAuthToken()` and `ParseJwtToken()` are provided by Hanzo IAM backend SDK.

The following code shows how to get and verify the access token. 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`

```go
// 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. Identify user with access token

:::info

This part is actually your application's own business logic and not part of OIDC, OAuth or Hanzo IAM. We just provide good practices as a lot of people don't know what to do for the next step.

:::

In Hanzo IAM, access token is usually identical as ID token. They are the same thing. So the access token contains all information for the logged-in user.

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

```go
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](/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

The Method to set session varies greatly depending on the language and web framework. E.g., Casnode
uses [Beego web framework](https://github.com/beego/beego/) and set session by calling: `c.SetSessionUser()`.

```go
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 Hanzo IAM is actually a JWT. So if your application uses JWT to keep user session, just use the access token directly for it:

1. Send the access token to frontend, save it in places like localStorage of the browser.
2. Let the browser send the access token to backend for every request.
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 `Hanzo IAM Public API` and not part of the OIDC or OAuth.

:::

Hanzo IAM Backend SDK provides a lot of helper functions, not limited to:

- `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 `Hanzo IAM Public API`. If a function is not in the Hanzo IAM Backend SDK, call the [Public API](/docs/basic/public-api) directly.

### 6. **(Optional)** Manage Applications via SDK

Hanzo IAM 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()`, Hanzo IAM 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.

How is this guide?

Last updated on

On this page