Add GitLab Sign-In to Your App

Enable "Sign in with GitLab" for your application's users through OAuth42's social authentication feature.

What You'll Build

In this tutorial, you'll configure GitLab as a social identity provider for your OAuth42 application. Your users will be able to click "Sign in with GitLab" and authenticate using their GitLab account.

How it works:

  • User clicks "Sign in with GitLab" in your app
  • OAuth42 redirects to GitLab for authentication
  • GitLab authenticates the user and returns to OAuth42
  • OAuth42 creates/links the user account and issues tokens to your app
  • Your app receives the tokens and the user is logged in

Great for DevOps and enterprise teams: GitLab is popular for DevOps teams and enterprises, especially those using self-hosted GitLab instances. Users trust GitLab and appreciate the quick sign-in experience.

Prerequisites

  • An OAuth42 account with an existing application
  • A GitLab account (gitlab.com or self-hosted instance)
  • Your application already integrated with OAuth42 (see Getting Started with Hosted Auth)

Step 1: Create a GitLab OAuth Application

  1. Go to GitLab User Settings → Applications
  2. Click Add new application
  3. Fill in the required fields:
    • Name: Your application name (shown to users during authorization)
    • Redirect URI: Set to the OAuth42 callback URL (see Step 2)
    • Confidential: Leave checked (recommended for server-side apps)
    • Scopes: Select read_user, openid, and email
  4. Click Save application

Self-hosted GitLab: If using a self-hosted GitLab instance, navigate to your instance URL followed by /-/user_settings/applications.

Step 2: Set the Redirect URI

GitLab needs to know where to redirect users after they authorize your app. Use the OAuth42 callback URL:

  • Production: https://api.oauth42.com/api/social-auth/callback
  • Development: https://localhost:8443/api/social-auth/callback

Multiple Redirect URIs: GitLab supports multiple redirect URIs. You can add both production and development URLs, each on a new line.

Step 3: Get Client Credentials

  1. After saving the application, you'll see your credentials
  2. Copy the Application ID (this is your Client ID)
  3. Copy the Secret (this is your Client Secret)

Copy the secret now! GitLab only shows the secret once. If you lose it, you'll need to regenerate it.

Step 4: Configure GitLab in OAuth42 Portal

Now configure GitLab as a social provider in your OAuth42 application:

  1. Log in to the OAuth42 Portal
  2. Navigate to Applications and select your application
  3. Click the Social Providers tab
  4. Click Add Provider
  5. Select GitLab from the dropdown
  6. Enter the Application ID you copied from GitLab
  7. Enter the Secret you copied from GitLab
  8. Click Add Provider to save

Secure Storage: Your GitLab Secret is automatically encrypted with AES-256 before being stored. It's never logged or exposed in plain text.

Step 5: Add GitLab Sign-In Button to Your App

If you're using OAuth42's hosted auth pages, the GitLab Sign-In button appears automatically when you enable the provider. No code changes needed!

For custom login pages, add a GitLab Sign-In button that initiates the social auth flow:

"use client"

import { useState } from 'react'

export default function LoginPage() {
  const [isLoading, setIsLoading] = useState(false)

  const handleGitLabSignIn = async () => {
    setIsLoading(true)

    // Call OAuth42's social auth init endpoint
    const response = await fetch('/api/auth/social/gitlab', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        provider: 'gitlab',
        client_id: process.env.NEXT_PUBLIC_OAUTH42_CLIENT_ID,
        is_signup: true, // Allow account creation
      }),
    })

    const data = await response.json()

    if (data.authorization_url) {
      // Redirect to GitLab
      window.location.href = data.authorization_url
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-100">
      <div className="max-w-md w-full space-y-6 p-8 bg-white rounded-lg shadow">
        <h1 className="text-2xl font-bold text-center">Sign In</h1>

        <button
          onClick={handleGitLabSignIn}
          disabled={isLoading}
          className="w-full flex items-center justify-center gap-3 py-3 px-4 bg-[#FC6D26] text-white rounded-lg hover:bg-[#E24329] transition-colors"
        >
          <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
            <path d="M4.845.904c-.435 0-.82.28-.955.692C2.639 5.449 1.246 9.728.07 13.335a1.437 1.437 0 00.522 1.607l11.071 8.045c.2.145.472.144.67-.004l11.073-8.04a1.436 1.436 0 00.522-1.61c-1.285-3.942-2.683-8.256-3.817-11.746a1.004 1.004 0 00-.957-.684.987.987 0 00-.949.69l-2.405 7.408H8.203l-2.41-7.408a.987.987 0 00-.942-.69h-.006z"/>
          </svg>
          {isLoading ? 'Redirecting...' : 'Continue with GitLab'}
        </button>

        <div className="relative">
          <div className="absolute inset-0 flex items-center">
            <div className="w-full border-t border-gray-300" />
          </div>
          <div className="relative flex justify-center text-sm">
            <span className="px-2 bg-white text-gray-500">or</span>
          </div>
        </div>

        {/* Your regular email/password login form */}
        <form className="space-y-4">
          <input
            type="email"
            placeholder="Email"
            className="w-full px-4 py-3 border border-gray-300 rounded-lg"
          />
          <input
            type="password"
            placeholder="Password"
            className="w-full px-4 py-3 border border-gray-300 rounded-lg"
          />
          <button
            type="submit"
            className="w-full py-3 px-4 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700"
          >
            Sign In
          </button>
        </form>
      </div>
    </div>
  )
}

Step 6: Create API Route for Social Auth (Custom Login Only)

If using a custom login page, create an API route to initiate the social auth flow:

mkdir -p app/api/auth/social/gitlab
touch app/api/auth/social/gitlab/route.ts

Add the following code to app/api/auth/social/gitlab/route.ts:

import { NextRequest, NextResponse } from 'next/server'

const API_BASE_URL = process.env.OAUTH42_ISSUER || 'https://api.oauth42.com'

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()

    const response = await fetch(`${API_BASE_URL}/api/social-auth/init`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        provider: 'gitlab',
        client_id: body.client_id,
        is_signup: body.is_signup || true,
        state: body.state,
      }),
    })

    const data = await response.json()

    if (!response.ok) {
      return NextResponse.json(data, { status: response.status })
    }

    return NextResponse.json(data)
  } catch (error) {
    console.error('[Social Auth] Error:', error)
    return NextResponse.json(
      { error: 'Failed to initiate social auth' },
      { status: 500 }
    )
  }
}

Using Hosted Auth? Skip this step! OAuth42's hosted auth pages automatically include the GitLab Sign-In button when you enable the provider.

Step 7: Test GitLab Sign-In

  1. Start your application
  2. Navigate to your login page
  3. Click "Continue with GitLab"
  4. You'll be redirected to GitLab's authorization page
  5. Sign in and authorize the application
  6. GitLab redirects back to OAuth42
  7. OAuth42 creates/links your user and redirects to your app
  8. You're now logged in!

Success! Your users can now sign in with their GitLab accounts.

How Account Linking Works

OAuth42 intelligently handles user accounts based on their GitLab profile:

New User (Signup)

A new user account is created with their GitLab profile info (name, email, avatar). The email must be verified on GitLab.

Existing GitLab User (Login)

If the GitLab account ID is already linked to a user, they're logged into that existing account.

Existing Email User

If a user with the same email already exists (from email/password signup or another provider), the GitLab account is linked to that existing account.

Multiple Social Providers

Users can link multiple social providers (Google, Apple, GitHub, GitLab, LinkedIn, X) to the same account, giving them flexibility in how they sign in.

Security Considerations

  • OAuth 2.0 + OpenID Connect: GitLab uses standard OAuth 2.0 with OpenID Connect support
  • State Parameter: CSRF protection via cryptographically random state tokens
  • Encrypted Storage: GitLab secrets are encrypted at rest using AES-256
  • Verified Emails: OAuth42 only accepts verified email addresses from GitLab
  • HTTPS Required: GitLab requires HTTPS for callback URLs (except localhost for development)

Troubleshooting

"Redirect URI mismatch" error

The callback URL doesn't match. Make sure you've added the exact OAuth42 callback URL in GitLab's application settings: https://api.oauth42.com/api/social-auth/callback

"GitLab social login not configured" error

The GitLab OAuth credentials are not configured for this application. Go to the OAuth42 Portal → Applications → Your App → Social Providers tab and verify that GitLab is configured with valid credentials.

"Failed to authenticate with GitLab" error

This usually means the Application ID or Secret is incorrect. Double-check your credentials in both the GitLab application settings and OAuth42 Portal.

"Email not verified" error

The user's email is not verified on GitLab. They need to verify their email in their GitLab account settings.

Self-Hosted GitLab Instances

OAuth42 currently supports gitlab.com. Support for self-hosted GitLab instances is planned for a future release. This will allow you to specify a custom GitLab URL when configuring the provider.

Need self-hosted GitLab support? Contact us to discuss your enterprise requirements.

Next Steps

Need Help?

Having trouble with GitLab Sign-In? Check our documentation or reach out to support.