DEV Community

Cover image for Introducing WorkOS: Add SSO, Magic Auth, or Social Auth in Minutes ⚡️🔐
Madza
Madza Subscriber

Posted on • Originally published at madza.hashnode.dev

Introducing WorkOS: Add SSO, Magic Auth, or Social Auth in Minutes ⚡️🔐

Adding enterprise features to your SaaS application can be the difference between landing major B2B clients and losing them to competitors.

However, building features like Single Sign-On (SSO), Magic Auth, Social Auth, and MFA from scratch typically takes months of development time and requires deep security expertise.

WorkOS solves this problem by providing a developer-friendly platform with pre-built APIs for adding enterprise-ready auth features to your applications.

In this guide, we'll build a demo application using NextJS that demonstrates how each WorkOS authentication feature works in practice. You'll learn how to:

  • Set up enterprise SSO for secure login

  • Add passwordless Magic Auth

  • Sign up using Social platform credentials

  • Enable multi-factor authentication (MFA)

  • Monitor security with WorkOS Radar (real-time threat detection)

By the end, you'll have working code examples you can adapt for your own applications!

Thanks to the WorkOS team for sponsoring this article!


Chapter 1: Understanding WorkOS and Its Core Features

WorkOS is a platform that handles enterprise authentication and user management for your application.

Think of it as "Stripe for enterprise features" - you integrate once, and WorkOS handles all the complexity of working with different identity providers, HR systems, and security protocols.

It comes with lots of useful features:

  • Single Sign-On (SSO) enables users to log in using their company's identity provider, such as Okta, Azure AD, or Google Workspace, eliminating separate passwords.

  • Magic Auth provides passwordless authentication through email verification codes, providing better security and a smoother user experience.

  • Social Auth allows users to sign up using their existing Google, Microsoft, Apple, or GitHub accounts.

  • Multi-Factor Authentication (MFA) provides an extra layer of security through authenticator apps, which enterprise customers are increasingly requiring.

  • WorkOS Radar is a useful security feature, a real-time threat detection system that monitors every authentication attempt, analyzing login locations, IP reputation, and much more.


Chapter 2: Setting up NextJS and .env Variables

Step 1: Create a new NextJS app

pnpm create next-app@latest workos-demo
Enter fullscreen mode Exit fullscreen mode

Choose these options for the CLI wizard:

  • TypeScript: Yes

  • ESLint: Yes

  • Tailwind CSS: Yes

  • App Router: Yes

  • Default import alias: No

cd workos-demo
Enter fullscreen mode Exit fullscreen mode

Step 2: Add WorkOS to the project

pnpm add @workos-inc/authkit-nextjs
Enter fullscreen mode Exit fullscreen mode

Step 3: Set Up Environment Variables

Create .env.local:

WORKOS_CLIENT_ID=your_workos_client_id
WORKOS_API_KEY=your_workos_api_key
Enter fullscreen mode Exit fullscreen mode

Get your Client ID and API key from dashboard.workos.com.

Client ID

Step 4: Create a simple Landing Page

Replace app/page.tsx:

export default async function Home() {
  return (
    <div className="min-h-screen bg-black flex items-center justify-center p-6">
      <div className="text-center space-y-10 max-w-2xl">

        <div className="space-y-4">
          <h1 className="text-5xl font-bold text-white tracking-tight">
            Auth Demo App
          </h1>
          <p className="text-xl text-neutral-400">
            Email + Password, Passwordless, Social Auth and MFA made easy with WorkOS.
          </p>
        </div>

        <div className="flex gap-4 justify-center">
          <a
            href="/login"
            className="px-8 py-3 bg-white text-black rounded-lg font-semibold hover:bg-neutral-200 transition-colors"
          >
            Sign In
          </a>
          <a
            href="/signup"
            className="px-8 py-3 bg-neutral-900 text-white border border-neutral-800 rounded-lg font-semibold hover:bg-neutral-800 transition-colors"
          >
            Sign Up
          </a>
        </div>
      </div>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

This code renders a centered, dark-themed homepage with a title, description, and styled "Sign In" and "Sign Up" buttons for an authentication demo app.

Step 5: Start your developer server:

pnpm dev
Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:3000 to see your landing page.

Localhost


Chapter 3: Create Auth Routes and a Protected Page

AuthKit makes authentication incredibly simple. Let's build the login and sign-up pages and create a protected page that will only be accessible after successful authentication.

Step 1: Create a sign-up route

Create app/signup/route.tsx:

import { getSignUpUrl } from '@workos-inc/authkit-nextjs';
import { redirect } from 'next/navigation';

export const GET = async () => {
    const signUpUrl = await getSignUpUrl();
    return redirect(signUpUrl);
};
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a login route

Create app/login/route.tsx:

import { getSignInUrl } from '@workos-inc/authkit-nextjs';
import { redirect } from 'next/navigation';

export const GET = async () => {
    const signInUrl = await getSignInUrl();

    return redirect(signInUrl);
};
Enter fullscreen mode Exit fullscreen mode

Step 3: Create a protected dashboard

Create app/dashboard/page.tsx:

import { withAuth, signOut } from '@workos-inc/authkit-nextjs';

export default async function Dashboard() {
    const { user } = await withAuth({ ensureSignedIn: true });

    return (
        <div className="min-h-screen bg-black p-8">
            <div className="max-w-4xl mx-auto">
                <div className="bg-neutral-900 border border-neutral-800 rounded-lg p-6 mb-6">
                    <h1 className="text-2xl font-bold text-white mb-2">Dashboard</h1>
                    <p className="text-neutral-400">
                        Welcome, {user.firstName || user.email}!
                    </p>
                </div>

                <div className="bg-neutral-900 border border-neutral-800 rounded-lg p-6 mb-6">
                    <h2 className="text-xl font-semibold text-white mb-4">Your Profile</h2>
                    <div className="space-y-2 text-sm text-neutral-400">
                        <p><span className="text-neutral-300">Email:</span> {user.email}</p>
                    </div>
                </div>

                <form
                    action={async () => {
                        'use server';
                        await signOut();
                    }}
                    className="mt-6"
                >
                    <button
                        type="submit"
                        className="px-6 py-2 rounded-lg font-semibold bg-[#ff6347] text-white hover:bg-[#e5533c] transition-colors cursor-pointer"
                    >
                        Sign Out
                    </button>
                </form>
            </div>
        </div >
    );
}
Enter fullscreen mode Exit fullscreen mode

This code displays a protected dashboard page that greets the authenticated user, displays a user email to test access to the user object, and renders a sign-out button to end the session.

With just a couple of withAuth() and signOut() functions, you have:

  • Protected routes that require authentication

  • Access to user information

  • Secure log-out functionality


Chapter 4: Add Middleware and Auth Callback

In this chapter, you'll set up the essential WorkOS integration steps to enable secure authentication and session management in your Next.js app.

Step 1: Add AuthKit middleware

Create middleware.ts in your project root:

import { authkitMiddleware } from '@workos-inc/authkit-nextjs';

export default authkitMiddleware();
Enter fullscreen mode Exit fullscreen mode

This middleware automatically handles session management for your entire app.

Step 2: Add AuthKit callback route

Create app/callback/route.ts:

import { handleAuth } from '@workos-inc/authkit-nextjs';

export const GET = handleAuth({ returnPathname: '/dashboard' });
Enter fullscreen mode Exit fullscreen mode

This code sets up the callback route so that, after authentication, WorkOS processes the response and redirects the user to the dashboard.

Step 3: Configure WorkOS redirects

Go to WorkOS Dashboard → Redirects and configure the following settings:

  • Add http://localhost:3000/callback as an allowed redirect URI

  • Set http://localhost:3000 as an app home page URL

  • Edit http://localhost:3000/login as a sign-in endpoint

  • Edit http://localhost:3000/login as a sign-out redirect endpoint

Login


Chapter 5: Authenticate via Single Sign-On (SSO)

Single Sign-On allows users to authenticate using their company's identity provider. In this chapter, we will take a look at how you can use it in your auth workflow.

First, navigate to the WorkOS dashboard and select the Organizations section.

You will notice that WorkOS has already created a test organization with the example.com domain that you can use to try out the SSO feature via the Test IdP.

IdP

To try it out in practice, check if your developer server is still running; if not, run pnpm dev again.

Open a new tab on your web browser and navigate to http://localhost:3000/login.

Provide a test email address ending with the Test IdP domain.

IdP

Hit continue, and you should be presented with the SSO account sign-up form.

This is the WorkOS test identity provider screen, where you can simulate an SSO login by entering user details (email, first name, last name, and group).

SSO

If you check back in the Users section, you can see that the user has been successfully created.

Users

Your users from that domain will now automatically use SSO instead of password authentication.

You can also add multiple SSO connections for different organizations. Navigate to the Organizations section, select Create Organization, and provide the organization name and domain.

Organizations


Chapter 6: Sign in via Email + Password

In this section, we'll sign up a new user through the traditional email + password method and see how the account is created and managed in the WorkOS dashboard.

Go to your sign-up page: http://localhost:3000/signup.

Provide your email address and a password.

Log-in

Hit Continue, and you will be successfully signed up.

Navigate to the Users section on the WorkOS dashboard and notice the user has been created.

Dashboard

You can further customize the password settings to match your specific requirements.

Navigate to Authentication → Methods → Email + Password → Manage.

Settings


Chapter 7: Setting up Magic Auth (Passwordless)

In this section, you'll enable and test Magic Auth to allow users to sign in securely without a password by using a one-time code sent to their email.

Make sure it’s enabled in the WorkOS settings: Authentication → Methods → Magic Auth → Enable.

Magic Auth

Go to your sign-up page: http://localhost:3000/signup.

Fill out the required fields and provide your email address.

Sign-up

Notice that in the next step, you will not be required to create the password.

Instead, check your inbox, and you will receive the verification code for the signup.

Verification

Finally, enter the received code, and you will be successfully logged in.

Success

Same as before, if you check the User section, you will see that the new user has been created.

New user


Chapter 8: Testing Social Authentication

If you do not want to sign in via SSO, email + password, or magic auth, you can also select to sign up using any of the most commonly used social credentials.

By default, four of the major providers are enabled.

You can customize this in Authentication → Providers and enable the ones you like.

Providers

Navigate to the sign-up page: http://localhost:3000/signup.

Instead of providing the email or the name, or surname, select one of the social providers.

Social

Depending on the social provider you picked, you will be asked to log in to your social account.

Modal

If the login was successful, you will see that the new user has been created.

Creation

You can also further customize each of the providers if you would like to create an auth with social credentials with a custom client ID and secret key.

Custom


Chapter 9: Enabling Multi-Factor Authentication (MFA)

MFA adds an extra layer of security by requiring a second verification method (like an authenticator app).

Enable MFA in Authentication → Features → Multi-Factor Auth.

Multifactor

Navigate to http://localhost:3000/login.

Fill out the login information as you normally do and try to sign in.

Info

This time, you will be notified to complete the MFA.

You can use auth apps like Passwords, Google Authenticator, or Microsoft Authenticator.

MFA

Open the auth app on your phone, scan the QR code, and enter the code provided by the app.

Then check the Users section and notice the user has been successfully created.

Done


Chapter 10: Check the Auth Requests via Radar

WorkOS Radar is an automatic threat detection system that monitors authentication attempts in real-time.

It analyzes login patterns, IP reputation, device fingerprints, and velocity to identify suspicious activity without any configuration on your part.

To see it in action, go to your WorkOS Dashboard and select the Radar section.

Sign in to your application at http://localhost:3000/login.

Return to the Radar dashboard to see the authentication event logged.

Radar

Scroll down, and you'll also see details about each login attempt, including IP address, location, domain names that were used, and users that triggered the events.

Details

For testing purposes, Radar typically marks normal development logins as low risk.

In production, it becomes more valuable as it learns your users' typical behavior patterns and can identify anomalies like impossible travel or credential stuffing attacks.


Chapter 11: Access User Authorization Details

User profile details

When a user authenticates through WorkOS, you receive their essential profile information, including email address, first name, last name, and a unique user ID.

WorkOS also tracks whether the user has verified their email and enrolled in multi-factor authentication, giving you complete visibility into their account security status.

Verified

Login session data

WorkOS manages secure, encrypted sessions automatically through AuthKit's middleware, eliminating the need for manual token handling or cookie configuration.

Each session includes the user's authentication state, organization membership (if applicable), and session metadata like creation time and expiration.

Session

Authentication event details

WorkOS tracks authentication events in real-time, including sign-ins, sign-ups, password changes, and MFA enrollments.

These events are automatically logged to your WorkOS dashboard, where you can monitor user activity, investigate security incidents, and ensure compliance with audit requirements.

Event


Chapter 12: Customize the Design to Your Liking

Signup, login, and password reset pages

WorkOS provides an authentication UI that you can fully customize to match your brand identity.

In the WorkOS Dashboard under the Branding section, you can upload your company logo, customize colors for buttons and backgrounds, adjust fonts, and much more for advanced styling.

Branding

Emails

All transactional emails sent by WorkOS, including verification codes, password resets, and magic auth links, can be customized to reflect your brand.

In the WorkOS Dashboard under the Branding section, you can configure the email templates with your brand colors, from logos, favicons, and backgrounds to fonts and links.

Emails


Conclusion

Building enterprise-ready authentication doesn't have to be complicated. With WorkOS, you've seen how quickly you can add professional authentication features to your Next.js application in minutes.

By leveraging a simple API, you've implemented secure user authentication, passwordless Magic Auth, multi-factor authentication, and real-time threat detection with Radar, all with minimal code.

The beauty of WorkOS lies in its simplicity. You don't need to worry about managing tokens, configuring cookies, or handling complex OAuth flows.

It handles the heavy lifting while giving you the flexibility to customize the authentication experience to match your brand and scales with you as your app grows.

You can now focus on building features that make your product unique, knowing that your authentication layer is secure, compliant, and battle-tested! Happy building and hope this was useful!


Did you like the article? Here is more 👇

Join 6,000+ others to receive the best DEV resources, tools, productivity tips, and career growth advice I discover by subscribing to my newsletter!

The Developer Toolbox

Also, connect with me on Twitter, LinkedIn, and GitHub!

Writing has always been my passion, and it gives me pleasure to help and inspire people. If you want to get featured or partner up, feel free to get in touch!

Top comments (0)