Authentication overview

GitLab provides various authentication mechanisms to secure access to its platform, covering both user interaction and programmatic access via its API. The choice of method depends on the specific use case, such as cloning repositories, interacting with the REST API, or integrating with third-party applications. GitLab supports standard protocols for identity and access management, including OAuth 2.0 for delegated authorization and SAML/LDAP for enterprise single sign-on (SSO) integrations.

For direct user access, GitLab allows authentication via username and password, often augmented with two-factor authentication (2FA) for enhanced security. For Git operations, SSH keys offer a secure and convenient alternative to HTTPS with credentials. When interacting with the GitLab API programmatically, Personal Access Tokens (PATs) are the primary method, providing fine-grained control over permissions and scope. OAuth 2.0 is specifically designed for scenarios where a third-party application needs to access GitLab resources on behalf of a user without handling their credentials directly, adhering to the OAuth 2.0 authorization framework for securing delegated access, as specified by the IETF RFC 6749.

Supported authentication methods

GitLab offers a range of authentication methods tailored for different scenarios, from individual developer operations to large-scale enterprise deployments. Understanding the strengths and appropriate use cases for each method is key to maintaining a secure and efficient development environment.

Method When to Use Security Level
Username and Password Web UI access, basic Git operations over HTTPS. Often combined with 2FA. Moderate (Enhanced with 2FA)
Two-Factor Authentication (2FA) Adds a second layer of security to username/password logins for the Web UI. High
Personal Access Tokens (PATs) API access, CI/CD pipelines, scripting, integrations. Provides granular scope control. High (Dependent on scope and expiry)
SSH Keys Secure Git operations (pull, push, clone) without repeatedly entering credentials. High (Based on key strength and passphrase protection)
OAuth 2.0 Third-party applications requesting access to GitLab resources on a user's behalf without storing credentials. High (Delegated authorization)
LDAP / Active Directory Enterprise environments for centralized user management and single sign-on (SSO). High (Integrates with existing identity infrastructure)
SAML / OpenID Connect Enterprise environments for single sign-on (SSO) with identity providers like Okta, Azure AD. High (Standardized SSO protocols)
Deploy Tokens Accessing private projects, container registries, or package registries from external systems or CI/CD jobs. Moderate (Specific to deployment needs, read-only or limited write)
Project Access Tokens Similar to PATs but scoped to a specific project, useful for project-level automation. High (Scoped access)
Group Access Tokens Similar to PATs but scoped to a specific group, useful for group-level automation. High (Scoped access)

Getting your credentials

The process for obtaining credentials varies depending on the authentication method you intend to use. GitLab's documentation provides specific instructions for each type of credential. For most common use cases, developers will primarily interact with Personal Access Tokens or SSH Keys.

Personal Access Tokens (PATs)

PATs are a versatile authentication method for API access, scripting, and CI/CD pipelines. To generate a PAT:

  1. Log in to your GitLab instance.
  2. Navigate to your user settings by clicking your avatar in the top right corner and selecting Preferences.
  3. In the left sidebar, select Access Tokens.
  4. Provide a descriptive name for your token and specify its expiration date. Setting an expiration date is a security best practice to limit the lifespan of the token.
  5. Select the scopes that define the permissions the token will have. For example, api for full API access, or more specific scopes like read_repository. Only grant the minimum necessary permissions.
  6. Click Create personal access token.

After creation, GitLab will display the token. Copy it immediately, as it will not be shown again. Treat PATs like passwords and store them securely, such as in a password manager or environment variables. For detailed instructions, refer to the GitLab documentation on creating personal access tokens.

SSH Keys

SSH keys provide a secure way to authenticate Git operations without needing to enter your username and password repeatedly. This involves generating a key pair on your local machine and adding the public key to your GitLab profile.

  1. Generate an SSH key pair: Open a terminal and run ssh-keygen -t ed25519 -C "[email protected]". Follow the prompts to save the key and optionally set a passphrase. The passphrase adds an extra layer of security to your private key. The GitHub documentation on generating SSH keys provides a general guide applicable to most Git hosting platforms.
  2. Copy your public SSH key: The public key is typically found in ~/.ssh/id_ed25519.pub (or id_rsa.pub if you used RSA). You can view its contents using cat ~/.ssh/id_ed25519.pub.
  3. Add the public key to GitLab:
    1. Log in to your GitLab instance.
    2. Navigate to your user settings by clicking your avatar and selecting Preferences.
    3. In the left sidebar, select SSH Keys.
    4. Paste your public key into the Key field.
    5. Add a descriptive Title (e.g., "My Work Laptop").
    6. Optionally, set an expiration date for the key.
    7. Click Add key.
  4. Verify the connection: In your terminal, run ssh -T [email protected]. You should receive a welcome message.

For more detailed information, consult the GitLab guide on configuring SSH keys.

OAuth 2.0 Applications

If you are developing a third-party application that needs to interact with GitLab on behalf of users, you will need to register an OAuth 2.0 application. This process typically involves:

  1. Logging into GitLab and navigating to User Settings > Applications.
  2. Clicking New application.
  3. Providing details such as Name, Redirect URI (callback URL), and Scopes.
  4. Upon creation, GitLab will provide a Application ID (Client ID) and a Secret (Client Secret). These credentials are used by your application to initiate the OAuth 2.0 flow.

The OAuth 2.0 authorization process involves redirecting the user to GitLab for approval, after which GitLab redirects the user back to your application with an authorization code. Your application then exchanges this code for an access token using the Client ID and Secret. This access token is then used to make API calls to GitLab on the user's behalf. More information on GitLab's OAuth 2.0 implementation can be found in the GitLab OAuth provider documentation.

Authenticated request example

This example demonstrates how to make an authenticated API request to GitLab using a Personal Access Token (PAT) to retrieve a list of projects. For this example, we'll use curl, a common command-line tool for making HTTP requests.

Prerequisites:

  • A GitLab Personal Access Token with at least the read_api or read_repository scope.
  • Your GitLab instance URL (e.g., https://gitlab.com or your self-hosted instance URL).

Example: List user projects using a PAT

Replace YOUR_PRIVATE_TOKEN with your actual Personal Access Token and YOUR_GITLAB_INSTANCE_URL with your GitLab instance URL.

curl --header "PRIVATE-TOKEN: YOUR_PRIVATE_TOKEN" \
     "YOUR_GITLAB_INSTANCE_URL/api/v4/projects"

Explanation:

  • --header "PRIVATE-TOKEN: YOUR_PRIVATE_TOKEN": This part adds an HTTP header named PRIVATE-TOKEN with your Personal Access Token as its value. This is how GitLab's API recognizes your authentication.
  • "YOUR_GITLAB_INSTANCE_URL/api/v4/projects": This is the endpoint for the GitLab API version 4 to list projects.

If successful, the command will return a JSON array containing information about the projects accessible to the token. If the token is invalid or lacks the necessary permissions, you will receive an error response, typically with a 401 Unauthorized or 403 Forbidden HTTP status code.

For more detailed API examples and available endpoints, refer to the GitLab API Reference.

Security best practices

Implementing strong authentication security is critical when working with GitLab to protect your code, infrastructure, and intellectual property. Adhering to these best practices can significantly reduce the risk of unauthorized access.

  • Enable Two-Factor Authentication (2FA): Always enable 2FA for all user accounts. This adds a crucial layer of security, requiring a second verification method (e.g., a code from an authenticator app) in addition to a password. GitLab supports various 2FA methods, including TOTP applications and WebAuthn (U2F) devices, as detailed in the GitLab 2FA guide.
  • Use Strong, Unique Passwords: Ensure all user accounts use complex, unique passwords that are not reused across other services. Password managers can assist with generating and storing strong passwords.
  • Limit Personal Access Token (PAT) Scopes: When creating PATs, grant only the minimum necessary permissions (scopes) required for the task. For example, if a token only needs to read repository data, do not grant api or write_repository access.
  • Set Expiration Dates for PATs and SSH Keys: Always set an expiration date for PATs and, where possible, for SSH keys. Regularly rotate these credentials before they expire. This limits the window of vulnerability if a credential is compromised.
  • Store Credentials Securely: Never hardcode PATs, SSH private keys, or other sensitive credentials directly into code, scripts, or configuration files that might be committed to version control. Use environment variables, secure secret management services (e.g., HashiCorp Vault, AWS Secrets Manager), or GitLab's built-in CI/CD variables (masked and protected) for storing and accessing sensitive information.
  • Regularly Revoke Unused Credentials: Periodically review and revoke any PATs, SSH keys, or OAuth applications that are no longer in use or belong to departed team members.
  • Monitor Audit Logs: Regularly review GitLab's audit logs to detect suspicious activity, such as unusual login attempts, changes to permissions, or unexpected API calls.
  • Use SSH Key Passphrases: Protect your SSH private keys with a strong passphrase. This encrypts the private key on your local machine, requiring the passphrase to decrypt it before use, even if the file itself is compromised.
  • Implement SSO with SAML/LDAP: For organizations, integrate GitLab with your existing Identity Provider (IdP) using SAML or LDAP. This centralizes user management, enforces corporate authentication policies, and simplifies user onboarding/offboarding.
  • Restrict Network Access: If self-hosting GitLab, restrict network access to the GitLab instance and its associated services (e.g., database) to only trusted IP addresses or networks.
  • Stay Updated: Keep your GitLab instance and any integrated tools updated to the latest stable versions to benefit from security patches and improvements.