Skip to content

Seamless Passwordless Authentication with React, Flask, and Authsignal

Posted in Education, and WhoCodeFirst

Magic link authentication provides a simple and secure way for users to log in without needing a password. In this guide, we’ll set up magic link authentication using React for the frontend, Flask for the backend, and Authsignal for handling authentication.

Prerequisites

  • Node.js and npm installed
  • Python and pip installed
  • Basic knowledge of React and Flask

Step 1: Setting Up the Backend with Flask

  1. Create a new Flask project:
   mkdir flask-auth
   cd flask-auth
   python -m venv venv
   source venv/bin/activate   # On Windows use `venv\Scripts\activate`
   pip install Flask
  1. Install additional dependencies:
   pip install authsignal flask-cors
  1. Create the Flask app (app.py):
   from flask import Flask, request, jsonify
   from flask_cors import CORS
   from authsignal import Authsignal

   app = Flask(__name__)
   CORS(app)

   # Initialize Authsignal
   authsignal = Authsignal(api_key="YOUR_AUTHSIGNAL_API_KEY")

   @app.route('/send-magic-link', methods=['POST'])
   def send_magic_link():
       data = request.json
       email = data.get('email')
       result = authsignal.magic_link.send(email)
       return jsonify(result)

   @app.route('/verify-magic-link', methods=['POST'])
   def verify_magic_link():
       data = request.json
       token = data.get('token')
       result = authsignal.magic_link.verify(token)
       return jsonify(result)

   if __name__ == '__main__':
       app.run(debug=True)
  1. Run the Flask app:
   python app.py

Step 2: Setting Up the Frontend with React

  1. Create a new React project:
   npx create-react-app react-auth
   cd react-auth
  1. Install Axios for API requests:
   npm install axios
  1. Create the authentication components:
  • Login Component (Login.js):
import React, { useState } from 'react';
import axios from 'axios';

const Login = () => {
  const [email, setEmail] = useState('');
  const [message, setMessage] = useState('');

  const sendMagicLink = async () => {
    try {
      const response = await axios.post('http://localhost:5000/send-magic-link', { email });
      setMessage(response.data.message);
    } catch (error) {
      setMessage('Error sending magic link');
    }
  };

  return (
    <div>
      <h2>Login</h2>
      <input
        type="email"
        placeholder="Enter your email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <button onClick={sendMagicLink}>Send Magic Link</button>
      <p>{message}</p>
    </div>
  );
};

export default Login;
  • Verify Component (Verify.js):
import React, { useState } from 'react';
import axios from 'axios';
import { useSearchParams } from 'react-router-dom';

const Verify = () => {
  const [searchParams] = useSearchParams();
  const token = searchParams.get('token');
  const [message, setMessage] = useState('');

  const verifyMagicLink = async () => {
    try {
      const response = await axios.post('http://localhost:5000/verify-magic-link', { token });
      setMessage(response.data.message);
    } catch (error) {
      setMessage('Error verifying magic link');
    }
  };

  React.useEffect(() => {
    if (token) {
      verifyMagicLink();
    }
  }, [token]);

  return (
    <div>
      <h2>Verify</h2>
      <p>{message}</p>
    </div>
  );
};

export default Verify;
  1. Update the main app component (App.js):
   import React from 'react';
   import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
   import Login from './Login';
   import Verify from './Verify';

   function App() {
     return (
       <Router>
         <div className="App">
           <Routes>
             <Route path="/" element={<Login />} />
             <Route path="/verify" element={<Verify />} />
           </Routes>
         </div>
       </Router>
     );
   }

   export default App;
  1. Run the React app:
   npm start

Step 3: Testing the Magic Link Flow

  1. Open the React app in your browser (usually at http://localhost:3000).
  2. Enter an email address and click “Send Magic Link”.
  3. Check the email for the magic link and click it. It should redirect to the verification route (http://localhost:3000/verify?token=YOUR_TOKEN).
  4. The Verify component will handle the verification and display the result.

Conclusion

You have now set up a simple magic link authentication system using React, Flask, and Authsignal. This setup can be expanded and customized to fit more complex authentication workflows and user management systems.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *