Appwrite Auth User Authentication: A Comprehensive Guide

Appwrite Auth User Authentication A Comprehensive Guide

Introduction

Appwrite Auth provides a complete end-to-end backend server with built-in user management and authentication capabilities. This allows developers to easily add signup, login, social auth, and user sessions to applications without setting up complex infrastructure.

In this in-depth tutorial, we will explore how to leverage Appwrite’s authentication system to:

  • Allow user signup, login, logout
  • Integrate social login with Google, Facebook etc.
  • Manage user sessions and cookies
  • Implement password reset workflows
  • Secure API routes and permissions
  • Build registration and login UI screens
  • Display username and avatar
  • Verify emailsaddresses
  • Handle forgot password flow

We’ll look at implementing these common auth workflows in a React app interfacing with Appwrite’s Auth and Users APIs. Let’s dive in!

Overview of Appwrite Auth

Appwrite handles user authentication via its Auth service. Out of the box, it provides:

  • Secure user registration with email/password or magic links
  • Built-in login pages and UI
  • Social login with Google, Facebook, Github etc.
  • Stateless JWT session handling
  • Customizable magic link emails
  • User profiles and metadata
  • Account verification and password reset
  • Granular permissions and roles
  • Integration with database rules for security

This allows implementing complete user auth without DevOps overhead. You can focus on building app functionality while offloading identity management to Appwrite.

Project Overview

To see Appwrite auth in action, we’ll build a React todo app with:

  • User registration
  • Login/logout
  • Social login with Google
  • Protected todo routes
  • User profile and avatar
  • Forgot password flow

The finished app code is available on GitHub.

We’ll use React for the frontend with Appwrite’s Auth, Users and Database APIs for the backend.

Initializing the Appwrite SDK

First, we need to initialize the Appwrite JavaScript SDK to integrate with the backend.

Create an account on appwrite.io and create a project. This will provide an endpoint and project ID.

In your React app, install the SDK:

npm install appwrite

Then initialize it:

import { Client } from 'appwrite';

const client = new Client();

client
  .setEndpoint('https://[HOSTNAME]/v1') // Your API endpoint
  .setProject('5df5acd0d48c2') // Your project ID
;

Now we can use client to make API calls. Let’s look at user management next.

Managing Users

Appwrite provides robust user management via the Users API.

Registration

To register a user:

const { id } = await client
  .users
  .create('[email]', '[password]');

This returns a unique user ID if successful.

Get Current User

When logged in, get the current user:

const { name, email, prefs } = await client.users.get();

Update User

Update the user’s account data:

await client.users.update('[ID]', {
  name: '[New name]'
});

This allows managing user accounts and metadata. Now let’s look at authentication.

Authenticating Users

The Auth API handles login, logout and session handling:

Register User

Same as Users API but also logs user in:

await client.auth.register('[email]', '[password]');

Login User

Log user in and return active session:

const { sessionId, expires } = await client.auth.login('[email]', '[password]');

Logout User

await client.auth.logout();

Revokes the current session.

Get Session Status

Check if user is logged in:

const { valid } = await client.auth.get();

With these basic building blocks, we can now implement authentication flows in our app.

Building a Registration and Login Flow

Let’s build user registration and login for our React todo app.

Registration Form

A simple controlled form:

function Register() {

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleSubmit = async e => {
    e.preventDefault();
    
    await client.auth.register(email, password);
    
    // Redirect to login 
  };

  return (
    <form onSubmit={handleSubmit}>
      <input 
        type="email"
        value={email} 
        onChange={e => setEmail(e.target.value)} 
      />

      <input
        type="password"
        value={password}
        onChange={e => setPassword(e.target.value)}  
      />

      <button type="submit">Register</button>
    </form>
  );

}

This allows creating a user account.

Login Form

Similar flow for login:

function Login() {

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleLogin = async (e) => {
    e.preventDefault();

    await client.auth.login(email, password);
    
    // Redirect to app
  };

  return (
    <form onSubmit={handleLogin}>
      <input  
        type="email"
        value={email}
        onChange={e => setEmail(e.target.value)}  
      />

      <input
        type="password"
        value={password} 
        onChange={e => setPassword(e.target.value)}
      />  

      <button type="submit">Login</button>
    </form>
  );

}

Now users can register and login!

Implementing Social Login

Appwrite also allows logging in via Google, Facebook, GitHub and other providers via OAuth.

Let’s add a Google login button:

function Login() {

  const handleGoogleLogin = async () => {
    await client.auth.loginOAuth2('google');
    // Redirect to app
  };
 
  return (
    <button onClick={handleGoogleLogin}>
      Log in with Google
    </button>
  );

}

That’s all we need to enable social login! Appwrite handles the OAuth flow behind the scenes.

Similarly, you can allow Facebook, GitHub, Bitbucket and other SSO providers.

Creating a User Profile

After login, we can display the user’s name and avatar on their profile:

function Profile() {

  const [user, setUser] = useState(null);

  useEffect(() => {
    const fetchUser = async () => {
      const { name, prefs } = await client.users.get();
      setUser({
        name,
        avatar: prefs.avatar // URL to image  
      });
    };
    fetchUser();
  }, []);

  if (!user) return null;

  return (
    <div>
      <img src={user.avatar} />
      <p>{user.name}</p>
    </div>
  );

}

The user preferences include the configured avatar image.

Implementing Forgot Password Flow

If a user forgets their password, we can implement a recovery flow:

Send Reset Email

await client.auth.recover(email);

This sends the user an email with reset instructions.

Set New Password

From the reset link, call:

await client.auth.updatePassword(user.id, newPassword, secret);

Where secret is the key from the reset URL.

This allows password recovery without exposing actual passwords.

Securing API Routes

We can use Appwrite rules to require a logged in user for endpoints:

client
  .database
  .createPermission(Permission.document('[collectionID]'))
  .read(Role.user()) // Require authenticated
;

Now requests to this collection will only succeed if the user is logged in.

Conclusion

In this guide, we saw how to leverage Appwrite’s authentication system to handle common identity workflows like:

  • User signup, login, social auth
  • Managing user accounts
  • Forgot password reset
  • Creating user profiles
  • Securing API routes

This provides a complete, customizable auth solution so you can focus your efforts on building app functionality.

The integration guides for platforms like React, Vue, and Flutter on Appwrite’s documentation show how to easily incorporate these same concepts across frameworks.

User management and authentication is a complex yet essential aspect of most applications. By offloading it entirely to Appwrite’s backend, you can painlessly add the auth layer while eliminating infrastructure overhead.

So give Appwrite’s authentication system a try for your next project!

Frequently Asked Questions

Q: Does Appwrite require managing authentication servers?

A: No, Appwrite provides a preconfigured auth service out of the box handled on their infrastructure.

Q: What authentication methods does Appwrite support?

A: Email+password, magic links, social logins with Google/Facebook/Github, and custom JWTs.

Q: Can you customize the auth UI and branding?

A: Yes, Appwrite provides JS SDK react components as well as endpoints to render the UI from scratch.

Q: How can I integrate the Authentication API into my frontend app?

A: Appwrite provides SDKs for JavaScript, React, Vue, Flutter, and more to call the Auth API from your client code.

Q: Does Appwrite scale to handle enterprise authentication needs?

A: Absolutely, Appwrite runs on Google Cloud infrastructure and is built to enterprise-grade scalability.

Q: Can Appwrite Auth integrate with an external user database?

A: Yes, you can develop a custom Appwrite function to connect to external user directories while still using Appwrite for session handling.

Q: What pricing models are available for Appwrite Auth?

A: Free generous forever plan, plus individual, team, and enterprise paid tiers. Fully open source too.

Leave a Reply

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