Giter VIP home page Giter VIP logo

casdoor-react-sdk's Introduction

casdoor-react-sdk

NPM version NPM download Github Actions Coverage Status Release Discord

It can help you quickly build a silent sign-in application based on Casdoor.

We have an implemented example: casdoor-spring-security-react-example.

To use this sdk just follow the steps below.

Installation

#NPM
npm i casdoor-react-sdk

#YARN
yarn add casdoor-react-sdk

Use in React

Let's take a look at the following example of a silent sign-in.

First, you need to initialize the Casdoor SDK.

import Sdk from "casdoor-js-sdk";

export const ServerUrl = "http://localhost:7023";

const sdkConfig = {
  serverUrl: "http://localhost:8000",
  clientId: "d79fd3c4e09a309fb3f5123",
  appName: "application_hnpzib",
  organizationName: "organization_4emn5k",
  redirectPath: "/callback",
  signinPath: "/api/signin",
};

export const CasdoorSDK = new Sdk(sdkConfig);

Then, intercept the /callback path in your application, the AuthCallback component will help you automatically handle the logic of interacting with the server, you just need to make sure that your server ServerUrl implements the ${ServerUrl}/api/signin api, and takes two parameters code and state, and returns token.

Note: Here you need to implement the saveTokenFromResponse and isGetTokenSuccessful functions.

  • isGetTokenSuccessful:you need to judge from the response data whether the request is processed successfully by the server.
  • saveTokenFromResponse:when your ${ServerUrl}/api/signin api successfully returns the token, you need to save the token.
import { Route, BrowserRouter, Routes } from "react-router-dom";
import { AuthCallback } from "casdoor-react-sdk";
import * as Setting from "./Setting";
import HomePage from "./HomePage";

function App() {
  const authCallback = (
    <AuthCallback
      sdk={Setting.CasdoorSDK}
      serverUrl={Setting.ServerUrl}
      saveTokenFromResponse={(res) => {
        // @ts-ignore
        // save token
        localStorage.setItem("token", res.data.accessToken);
      }}
      isGetTokenSuccessful={(res) => {
        // @ts-ignore
        // according to the data returned by the server,
        // determine whether the `token` is successfully obtained through `code` and `state`.
        return res.success === true;
      }}
    />
  );

  return (
    <BrowserRouter>
      <Routes>
        <Route path="/callback" element={authCallback} />
        <Route path="/" element={<HomePage />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;

In your HomePage to determine whether you need to log in silently, if you need to log in silently, return the SilentSignin component, it will help you initiate a login request, and after the login is successful, it will call the handleReceivedSilentSigninSuccessEvent function, and when the login fails, it will also Call the handleReceivedSilentSigninFailureEvent function.

import * as Setting from "./Setting";
import { SilentSignin, isSilentSigninRequired } from "casdoor-react-sdk";

function HomePage() {
  const isLoggedIn = () => {
    return localStorage.getItem("token") !== null;
  };

  if (isSilentSigninRequired()) {
    // if the `silentSignin` parameter exists, perform silent login processing
    return (
      <SilentSignin
        sdk={Setting.CasdoorSDK}
        isLoggedIn={isLoggedIn}
        handleReceivedSilentSigninSuccessEvent={() => {
          // jump to the home page here and clear silentSignin parameter
          window.location.href = "/";
        }}
        handleReceivedSilentSigninFailureEvent={() => {
          // prompt the user to log in failed here
          alert("login failed");
        }}
      />
    );
  }

  const renderContent = () => {
    if (isLoggedIn()) {
      return <div>Hello!</div>;
    } else {
      return <div>you are not logged in</div>;
    }
  };

  return renderContent();
}

export default HomePage;

casdoor-react-sdk's People

Contributors

hsluoyz avatar irvanmohamad avatar selflocking avatar wenxuan70 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

casdoor-react-sdk's Issues

Can't Signin silently

I can't signin silently by using SilentSignin component, it always run into handleReceivedSilentSigninFailureEvent callback.

I tried to use casdoor-js-sdk by calling sdk.silentSignin(...) , it's failed too.

I log out an url about sdk.getSigninUrl()+"&silentSignin=1, it will redirect to my app host and with code & state params.

maybe there's some problem about iframe inject?

Request to update to casdoor-js-sdk v0.10.0

Hey, it would be great if you could update to casdoor-js-sdk v0.10.0:

  1. package.json

"casdoor-js-sdk": "^0.10.0",

  1. README.md
const sdkConfig = {
  serverUrl: "http://localhost:8000",
  clientId: "d79fd3c4e09a309fb3f5123",
  appName: "application_hnpzib",
  organizationName: "organization_4emn5k",
  redirectPath: "/callback",
  signinPath: "/api/signin",
};

//...
//...
//...

function App() {
  const authCallback = (
    <AuthCallback
      sdk={Setting.CasdoorSDK}
      serverUrl={Setting.ServerUrl}
      saveTokenFromResponse={(res) => {
        // @ts-ignore
        // save token
        localStorage.setItem("token", res.data.accessToken);
      }}
      isGetTokenSuccessful={(res) => {
        // @ts-ignore
        // according to the data returned by the server,
        // determine whether the `token` is successfully obtained through `code` and `state`.
        return res.success === true;
      }}
    />
  );

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.