All Projects → koole → react-sanctum

koole / react-sanctum

Licence: MIT license
Easily hook up your React app to Laravel Sanctum and Laravel Fortify

Programming Languages

PHP
23972 projects - #3 most used programming language
typescript
32286 projects
Blade
752 projects
javascript
184084 projects - #8 most used programming language
HTML
75241 projects
shell
77523 projects

Projects that are alternatives of or similar to react-sanctum

sanctum-react-spa
A React app that authenticates with the Laravel Sanctum package.
Stars: ✭ 26 (-74%)
Mutual labels:  sanctum, laravel-sanctum
microblog-authy
Microblog application from the Flask Mega-Tutorial with added two-factor push authentication via Authy
Stars: ✭ 26 (-74%)
Mutual labels:  two-factor-authentication
otp-java
A small and easy-to-use one-time password generator library for Java according to RFC 4226 (HOTP) and RFC 6238 (TOTP).
Stars: ✭ 107 (+7%)
Mutual labels:  two-factor-authentication
dumb-bem
Simple BEM react components generator
Stars: ✭ 32 (-68%)
Mutual labels:  react-components
socket.io-react
A High-Order component to connect React and Socket.io easily
Stars: ✭ 67 (-33%)
Mutual labels:  react-components
Laravel---SB-Admin-2---Fortify
Ini adalah template dasar untuk menggunakan SB Admin 2 yang dibungkus dengan Laravel 9, Laravel UI, dan Laravel Fortify.
Stars: ✭ 22 (-78%)
Mutual labels:  laravel-fortify
laravel-two-factor-authentication
A two-factor authentication package for Laravel >= 8
Stars: ✭ 37 (-63%)
Mutual labels:  two-factor-authentication
totp
Time-Based One-Time Password Code Generator
Stars: ✭ 76 (-24%)
Mutual labels:  two-factor-authentication
best-of-react
🏆 A ranked list of awesome React open-source libraries and tools. Updated weekly.
Stars: ✭ 364 (+264%)
Mutual labels:  react-components
frontend-toolbox
Frontend tools which we used in snappmarket v2
Stars: ✭ 37 (-63%)
Mutual labels:  react-components
shared-react-components-example
An example of a mono-repository of shared React components libraries!
Stars: ✭ 85 (-15%)
Mutual labels:  react-components
react-fundamentals
React fundamentals
Stars: ✭ 15 (-85%)
Mutual labels:  react-components
Three-Factor-Security-Door
What do you get when you mix a Raspberry Pi, a MySQL database, an RFID reader, an LCD touchscreen, a relay switch, an electronic door strike and a Twilio SMS account?
Stars: ✭ 49 (-51%)
Mutual labels:  two-factor-authentication
boilerplate-react-redux-pwa
It's sample boilerplate with pwa + react + redux + redux-saga
Stars: ✭ 14 (-86%)
Mutual labels:  react-components
apache 2fa
Apache two-factor (2FA) authentication with Google Authenticator based on Time-based One-Time Password (TOTP) or HMAC-based one-time password (HOTP) Algorithms.
Stars: ✭ 63 (-37%)
Mutual labels:  two-factor-authentication
superglue
A productive library for Classic Rails, React and Redux
Stars: ✭ 106 (+6%)
Mutual labels:  react-components
google-authenticator
Google Authenticator
Stars: ✭ 20 (-80%)
Mutual labels:  two-factor-authentication
cnode-react
a web app for cnode.org with react + react-router + react-redux
Stars: ✭ 23 (-77%)
Mutual labels:  react-components
resource-center
New version of the resource center built with ReactJS
Stars: ✭ 89 (-11%)
Mutual labels:  react-components
Registration-and-Login-using-MERN-stack
Simple Registration and Login component with MERN stack
Stars: ✭ 210 (+110%)
Mutual labels:  react-components

Logo Laravel Sanctum

Build Status npm npm npm bundle size GitHub

Introduction

React Sanctum package provides an easy way to authenticate your React application with Laravel Sanctum.

  • Easily hook up your React app to Laravel Sanctum
  • Works with both hooks and class components
  • Built in support for two factor authentication with Laravel Fortify
  • Just one dependency: axios

Usage

Install from NPM

npm i react-sanctum

Wrap your application in an <Sanctum> component

Example

import React from "react";

import { Sanctum } from "react-sanctum";

const sanctumConfig = {
  apiUrl: "http://foobar.test",
  csrfCookieRoute: "sanctum/csrf-cookie",
  signInRoute: "login",
  signOutRoute: "logout",
  userObjectRoute: "user",
};

const App = () => (
  <div className="my-application">
    <Sanctum config={sanctumConfig}>/* Your application code */</Sanctum>
  </div>
);

You can then use the useSanctum() hook to get authentication status, user data and sanctum related methods in any component.

import React from "react";
import { useSanctum } from "react-sanctum";

const LoginButton = () => {
  const { authenticated, user, signIn } = useSanctum();

  const handleLogin = () => {
    const email = "[email protected]";
    const password = "example";
    const remember = true;

    signIn(email, password, remember)
      .then(() => window.alert("Signed in!"))
      .catch(() => window.alert("Incorrect email or password"));
  };

  if (authenticated === true) {
    return <h1>Welcome, {user.name}</h1>;
  } else {
    return <button onClick={handleLogin}>Sign in</button>;
  }
};

export default LoginButton;

Or use the withSanctum() higher-order component to get these same values.

import React from "react";
import { withSanctum } from "react-sanctum";

const LoginButton = ({ authenticated, user, signIn }) => {
    ...
};

export default withSanctum(LoginButton);

You can also directly consume the Sanctum context by importing SanctumContext.

The useSanctum hook and the withSanctum HOC give you access to the SanctumContext, which contains the following data and methods:

Description
user Object your API returns with user data
authenticated Boolean, or null if authentication has not yet been checked
signIn() Accepts (email, password, remember?), returns a promise, resolves with {twoFactor: boolean, signedIn: boolean, user: {}}.
signOut() Returns a promise
setUser() Accepts (user, authenticated?), allows you to manually set the user object and optionally its authentication status (boolean).
twoFactorChallenge() Accepts (code, recovery?), returns a promise, resolves with the user object.
checkAuthentication() Returns the authentication status. If it's null, it will ask the server and update authenticated.

Setup

All URLS in the config are required. These need to be created in your Laravel app.

const sanctumConfig = {
  // Your application URL
  apiUrl: "http://foobar.test",
  // The following settings are URLS that need to be created in your Laravel application
  // The URL sanctum uses for the csrf cookie
  csrfCookieRoute: "sanctum/csrf-cookie",
  // {email: string, password: string, remember: true | null} get POSTed to here
  signInRoute: "api/login",
  // A POST request is sent to this route to sign the user out
  signOutRoute: "api/logout",
  // Used (GET) for checking if the user is signed in (so this should be protected)
  // The returned object will be avaiable as `user` in the React components.
  userObjectRoute: "api/user",
  // The URL where the OTAP token or recovery code will be sent to (optional).
  // Only needed if you want to use two factor authentication.
  twoFactorChallengeRoute: "two-factor-challenge",
  // An axios instance to be used by react-sanctum (optional). Useful if you for example need to add custom interceptors.
  axiosInstance: AxiosInstance,
  // Optional key used for the username POSTed to Laravel, defaults to "email". 
  usernameKey: "email";
};

react-sanctum automatically checks if the user is signed in when the the <Sanctum> component gets mounted. If you don't want this, and want to manually use the checkAuthentication function later, set checkOnInit to false like so:

<Sanctum config={sanctumConfig} checkOnInit={false}>

Handling registration

Methods for signIn and signOut are provided by this library. Registration is not included as there seem to be many ways people handle registration flows.

If you want to sign in your user after registration, there's an easy way to do this. First, make sure the endpoint you post the registration data to signs in the user (Auth::guard()->login(...)) and have it return the user object to the front-end.

In your front-end you can then pass this user object into the setUser() function, et voilà, your new user has been signed in.

For example:

axios
    .post(`${API_URL}/register`, data)
    .then(function (response) {
        const user = response.data;
        setUser(user); // The react-sanctum setUser function
        ...
    })
    .catch(function (error) {
        ...
    });

Two factor authentication

This package supports two factor authentication using Laravel Fortify out of the box.

  1. Install Laravel Fortify using the following instructions https://laravel.com/docs/8.x/fortify#installation

  2. Add the TwoFactorAuthenticable trait to the User model https://laravel.com/docs/8.x/fortify#two-factor-authentication

  3. Make sure the two-factor-challenge route is included in the config/cors.php file.

Example for implementation:

import React, { useState } from "react";
import { useSanctum } from "react-sanctum";

const Login = () => {
  const [showTwoFactorForm, setShowTwoFactorForm] = useState(false);
  const [code, setCode] = useState("");
  const [recoveryCode, setRecoveryCode] = useState("");
  const { authenticated, user, signIn, twoFactorChallenge } = useSanctum();

  const handleLogin = () => {
    const email = "[email protected]";
    const password = "password";
    const remember = true;

    signIn(email, password, remember)
      .then(({ twoFactor }) => {
        if (twoFactor) {
          setShowTwoFactorForm(true);
          return;
        }

        window.alert("Signed in without token!");
      })
      .catch(() => window.alert("Incorrect email or password"));
  };

  const handleTwoFactorChallenge = (recovery = false) => {
    twoFactorChallenge(recovery ? recoveryCode : code, recovery)
      .then(() => window.alert("Signed in with token!"))
      .catch(() => window.alert("Incorrect token"));
  };

  if (authenticated === true) {
    return <h1>Welcome, {user.name}</h1>;
  } else {
    if (showTwoFactorForm) {
      return (
        <div>
          <input
            type="text"
            onInput={(event) => setCode(event.currentTarget.value)}
          />
          <button onClick={() => handleTwoFactorChallenge()}>
            Sign in using OTAP-token
          </button>
          <hr />
          <input
            type="text"
            onInput={(event) => setRecoveryCode(event.currentTarget.value)}
          />
          <button onClick={() => handleTwoFactorChallenge(true)}>
            Sign in using recovery token
          </button>
        </div>
      );
    }

    return <button onClick={handleLogin}>Sign in</button>;
  }
};

export default Login;

Axios

Quick tip for people using axios: react-sanctum uses Axios for making requests to your server. If your project is also using axios, make sure to set axios.defaults.withCredentials = true;. That way axios will authenticate your requests to the server properly.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].