grafana setup weight 600 Learn how to configure SAML authentication in Grafana s UI products title Configure SAML authentication using the Grafana user interface menuTitle SAML user interface labels cloud enterprise

Answer:
---
description: Learn how to configure SAML authentication in Grafana's UI.
labels:
  products:
    - cloud
    - enterprise
menuTitle: SAML user interface
title: Configure SAML authentication using the Grafana user interface
weight: 600
---

# Configure SAML authentication using the Grafana user interface

Available in [Grafana Enterprise]() version 10.0 and later, and [Grafana Cloud Pro and Advanced](/docs/grafana-cloud/).

You can configure SAML authentication in Grafana through the user interface (UI) or the Grafana configuration file. For instructions on how to set up SAML using the Grafana configuration file, refer to [Configure SAML authentication using the configuration file]().

The Grafana SAML UI provides the following advantages over configuring SAML in the Grafana configuration file:

- It is accessible by Grafana Cloud users
- SAML UI carries out input validation and provides useful feedback on the correctness of the configuration, making SAML setup easier
- It doesn't require Grafana to be restarted after a configuration update
- Access to the SAML UI only requires access to authentication settings, so it can be used by users with limited access to Grafana's configuration

Any configuration changes made through the Grafana user interface (UI) will take precedence over settings specified in the Grafana configuration file or through environment variables. This means that if you modify any configuration settings in the UI, they will override any corresponding settings set via environment variables or defined in the configuration file. For more information on how Grafana determines the order of precedence for its settings, please refer to the [Settings update at runtime]().

Disabling the UI does not affect any configuration settings that were previously set up through the UI. Those settings will continue to function as intended even with the UI disabled.

## Before you begin

To follow this guide, you need:

- Knowledge of SAML authentication. Refer to [SAML authentication in Grafana]() for an overview of Grafana's SAML integration.
- Permissions `settings:read` and `settings:write` with scope `settings:auth.saml:*` that allow you to read and update SAML authentication settings.

  These permissions are granted by `fixed:authentication.config:writer` role.
  By default, this role is granted to Grafana server administrator in self-hosted instances and to Organization admins in Grafana Cloud instances.

- Grafana instance running Grafana version 10.0 or later with [Grafana Enterprise]() or [Grafana Cloud Pro or Advanced](/docs/grafana-cloud/) license.

It is possible to set up Grafana with SAML authentication using Azure AD. However, if an Azure AD user belongs to more than 150 groups, a Graph API endpoint is shared instead.

Grafana versions 11.1 and below do not support fetching the groups from the Graph API endpoint. As a result, users with more than 150 groups will not be able to retrieve their groups. Instead, it is recommended that you use OIDC/OAuth workflows.

As of Grafana 11.2, the SAML integration offers a mechanism to retrieve user groups from the Graph API.

Related links:

- [Azure AD SAML limitations](https://learn.microsoft.com/en-us/entra/identity-platform/id-token-claims-reference#groups-overage-claim)
- [Set up SAML with Azure AD]()
- [Configure a Graph API application in Azure AD]()

## Steps To Configure SAML Authentication

Sign in to Grafana and navigate to **Administration > Authentication > Configure SAML**.

### 1. General Settings Section

1. Complete the **General settings** fields.

   For assistance, consult the following table for additional guidance about certain fields:

   | Field                                 | Description                                                                                |
   | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
   | **Allow signup**                      | If enabled, you can create new users through the SAML login. If disabled, then only existing Grafana users can log in with SAML.                                                                                |
   | **Auto login**                        | If enabled, Grafana will attempt to automatically log in with SAML skipping the login screen.                                                                                |
   | **Single logout**                     | The SAML single logout feature enables users to log out from all applications associated with the current IdP session established using SAML SSO. For more information, refer to [SAML single logout documentation]](). |
   | **Identity provider initiated login** | Enables users to log in to Grafana directly from the SAML IdP. For more information, refer to [IdP initiated login documentation]().                                                                 |

1. Click **Next: Sign requests**.

### 2. Sign Requests Section

1. In the **Sign requests** field, specify whether you want the outgoing requests to be signed, and, if so, then:

   1. Provide a certificate and a private key that will be used by the service provider (Grafana) and the SAML IdP.

      Use the [PKCS #8](https://en.wikipedia.org/wiki/PKCS_8) format to issue the private key.

      For more information, refer to an [example on how to generate SAML credentials]().

      Alternatively, you can generate a new private key and certificate pair directly from the UI. Click on the `Generate key and certificate` button to open a form where you enter some information you want to be embedded into the new certificate.

   1. Choose which signature algorithm should be used.

      The SAML standard recommends using a digital signature for some types of messages, like authentication or logout requests to avoid [man-in-the-middle attacks](https://en.wikipedia.org/wiki/Man-in-the-middle_attack).

1. Click **Next: Connect Grafana with Identity Provider**.

### 3. Connect Grafana with Identity Provider Section

1. Configure IdP using Grafana Metadata
   1. Copy the **Metadata URL** and provide it to your SAML IdP to establish a connection between Grafana and the IdP.
      - The metadata URL contains all the necessary information for the IdP to establish a connection with Grafana.
   1. Copy the **Assertion Consumer Service URL** and provide it to your SAML IdP.
      - The Assertion Consumer Service URL is the endpoint where the IdP sends the SAML assertion after the user has been authenticated.
   1. If you want to use the **Single Logout** feature, copy the **Single Logout Service URL** and provide it to your SAML IdP.
1. Finish configuring Grafana using IdP data
   1. Provide IdP Metadata to Grafana.
   - The metadata contains all the necessary information for Grafana to establish a connection with the IdP.
   - This can be provided as Base64-encoded value, a path to a file, or as a URL.
1. Click **Next: User mapping**.

### 4. User Mapping Section

1. If you wish to [map user information from SAML assertions](), complete the **Assertion attributes mappings** section.

   You also need to configure the **Groups attribute** field if you want to use group synchronization. Group sync allows you to automatically map users to Grafana teams or role-based access control roles based on their SAML group membership.
   To learn more about how to configure group synchronization, refer to [Configure team sync]() and [Configure group attribute sync](https://grafana.com/docs/grafana/<GRAFANA_VERSION>/setup-grafana/configure-security/configure-group-attribute-sync) documentation.

1. If you want to automatically assign users' roles based on their SAML roles, complete the **Role mapping** section.

   First, you need to configure the **Role attribute** field to specify which SAML attribute should be used to retrieve SAML role information.
   Then enter the SAML roles that you want to map to Grafana roles in **Role mapping** section. If you want to map multiple SAML roles to a Grafana role, separate them by a comma and a space. For example, `Editor: editor, developer`.

   Role mapping will automatically update user's [basic role]() based on their SAML roles every time the user logs in to Grafana.
   Learn more about [SAML role synchronization]().

1. If you're setting up Grafana with Azure AD using the SAML protocol and want to fetch user groups from the Graph API, complete the **Azure AD Service Account Configuration** subsection.
   1. Set up a service account in Azure AD and provide the necessary details in the **Azure AD Service Account Configuration** section.
   1. Provide the **Client ID** of your Azure AD application.
   1. Provide the **Client Secret** of your Azure AD application, the **Client Secret** will be used to request an access token from Azure AD.
   1. Provide the Azure AD request **Access Token URL**.
   1. If you don't have users with more than 150 groups, you can still force the use of the Graph API by enabling the **Force use Graph API** toggle.
1. If you have multiple organizations and want to automatically add users to organizations, complete the **Org mapping section**.

   First, you need to configure the **Org attribute** field to specify which SAML attribute should be used to retrieve SAML organization information.
   Now fill in the **Org mapping** field with mappings from SAML organization to Grafana organization. For example, `Org mapping: Engineering:2, Sales:2` will map users who belong to `Engineering` or `Sales` organizations in SAML to Grafana organization with ID 2.
   If you want users to have different roles in different organizations, you can additionally specify a role. For example, `Org mapping: Engineering:2:Editor` will map users who belong to `Engineering` organizations in SAML to Grafana organization with ID 2 and assign them Editor role.

   Organization mapping will automatically update user's organization memberships (and roles, if they have been configured) based on their SAML organization every time the user logs in to Grafana.
   Learn more about [SAML organization mapping]().

1. If you want to limit the access to Grafana based on user's SAML organization membership, fill in the **Allowed organizations** field.
1. Click **Next: Test and enable**.

### 5. Test And Enable Section

1. Click **Save and enable**
   - If there are issues with your configuration, an error message will appear. Refer back to the previous steps to correct the issues and click on `Save and apply` on the top right corner once you are done.
1. If there are no configuration issues, SAML integration status will change to `Enabled`.
   Your SAML configuration is now enabled.
1. To disable SAML integration, click `Disable` in the top right corner.

description  Learn how to configure SAML authentication in Grafana s UI  labels    products        cloud       enterprise menuTitle  SAML user interface title  Configure SAML authentication using the Grafana user interface weight  600        Configure SAML authentication using the Grafana user interface   Available in  Grafana Enterprise    version 10 0 and later  and  Grafana Cloud Pro and Advanced   docs grafana cloud      You can configure SAML authentication in Grafana through the user interface  UI  or the Grafana configuration file  For instructions on how to set up SAML using the Grafana configuration file  refer to  Configure SAML authentication using the configuration file      The Grafana SAML UI provides the following advantages over configuring SAML in the Grafana configuration file     It is accessible by Grafana Cloud users   SAML UI carries out input validation and provides useful feedback on the correctness of the configuration  making SAML setup easier   It doesn t require Grafana to be restarted after a configuration update   Access to the SAML UI only requires access to authentication settings  so it can be used by users with limited access to Grafana s configuration   Any configuration changes made through the Grafana user interface  UI  will take precedence over settings specified in the Grafana configuration file or through environment variables  This means that if you modify any configuration settings in the UI  they will override any corresponding settings set via environment variables or defined in the configuration file  For more information on how Grafana determines the order of precedence for its settings  please refer to the  Settings update at runtime        Disabling the UI does not affect any configuration settings that were previously set up through the UI  Those settings will continue to function as intended even with the UI disabled       Before you begin  To follow this guide  you need     Knowledge of SAML authentication  Refer to  SAML authentication in Grafana    for an overview of Grafana s SAML integration    Permissions  settings read  and  settings write  with scope  settings auth saml    that allow you to read and update SAML authentication settings     These permissions are granted by  fixed authentication config writer  role    By default  this role is granted to Grafana server administrator in self hosted instances and to Organization admins in Grafana Cloud instances     Grafana instance running Grafana version 10 0 or later with  Grafana Enterprise    or  Grafana Cloud Pro or Advanced   docs grafana cloud   license    It is possible to set up Grafana with SAML authentication using Azure AD  However  if an Azure AD user belongs to more than 150 groups  a Graph API endpoint is shared instead   Grafana versions 11 1 and below do not support fetching the groups from the Graph API endpoint  As a result  users with more than 150 groups will not be able to retrieve their groups  Instead  it is recommended that you use OIDC OAuth workflows   As of Grafana 11 2  the SAML integration offers a mechanism to retrieve user groups from the Graph API   Related links      Azure AD SAML limitations  https   learn microsoft com en us entra identity platform id token claims reference groups overage claim     Set up SAML with Azure AD       Configure a Graph API application in Azure AD           Steps To Configure SAML Authentication  Sign in to Grafana and navigate to   Administration   Authentication   Configure SAML         1  General Settings Section  1  Complete the   General settings   fields      For assistance  consult the following table for additional guidance about certain fields        Field                                   Description                                                                                Allow signup                          If enabled  you can create new users through the SAML login  If disabled  then only existing Grafana users can log in with SAML                                                                                Auto login                            If enabled  Grafana will attempt to automatically log in with SAML skipping the login screen                                                                                Single logout                         The SAML single logout feature enables users to log out from all applications associated with the current IdP session established using SAML SSO  For more information  refer to  SAML single logout documentation               Identity provider initiated login     Enables users to log in to Grafana directly from the SAML IdP  For more information  refer to  IdP initiated login documentation                                                                        1  Click   Next  Sign requests         2  Sign Requests Section  1  In the   Sign requests   field  specify whether you want the outgoing requests to be signed  and  if so  then      1  Provide a certificate and a private key that will be used by the service provider  Grafana  and the SAML IdP         Use the  PKCS  8  https   en wikipedia org wiki PKCS 8  format to issue the private key         For more information  refer to an  example on how to generate SAML credentials            Alternatively  you can generate a new private key and certificate pair directly from the UI  Click on the  Generate key and certificate  button to open a form where you enter some information you want to be embedded into the new certificate      1  Choose which signature algorithm should be used         The SAML standard recommends using a digital signature for some types of messages  like authentication or logout requests to avoid  man in the middle attacks  https   en wikipedia org wiki Man in the middle attack    1  Click   Next  Connect Grafana with Identity Provider         3  Connect Grafana with Identity Provider Section  1  Configure IdP using Grafana Metadata    1  Copy the   Metadata URL   and provide it to your SAML IdP to establish a connection between Grafana and the IdP          The metadata URL contains all the necessary information for the IdP to establish a connection with Grafana     1  Copy the   Assertion Consumer Service URL   and provide it to your SAML IdP          The Assertion Consumer Service URL is the endpoint where the IdP sends the SAML assertion after the user has been authenticated     1  If you want to use the   Single Logout   feature  copy the   Single Logout Service URL   and provide it to your SAML IdP  1  Finish configuring Grafana using IdP data    1  Provide IdP Metadata to Grafana       The metadata contains all the necessary information for Grafana to establish a connection with the IdP       This can be provided as Base64 encoded value  a path to a file  or as a URL  1  Click   Next  User mapping         4  User Mapping Section  1  If you wish to  map user information from SAML assertions     complete the   Assertion attributes mappings   section      You also need to configure the   Groups attribute   field if you want to use group synchronization  Group sync allows you to automatically map users to Grafana teams or role based access control roles based on their SAML group membership     To learn more about how to configure group synchronization  refer to  Configure team sync    and  Configure group attribute sync  https   grafana com docs grafana  GRAFANA VERSION  setup grafana configure security configure group attribute sync  documentation   1  If you want to automatically assign users  roles based on their SAML roles  complete the   Role mapping   section      First  you need to configure the   Role attribute   field to specify which SAML attribute should be used to retrieve SAML role information     Then enter the SAML roles that you want to map to Grafana roles in   Role mapping   section  If you want to map multiple SAML roles to a Grafana role  separate them by a comma and a space  For example   Editor  editor  developer       Role mapping will automatically update user s  basic role    based on their SAML roles every time the user logs in to Grafana     Learn more about  SAML role synchronization      1  If you re setting up Grafana with Azure AD using the SAML protocol and want to fetch user groups from the Graph API  complete the   Azure AD Service Account Configuration   subsection     1  Set up a service account in Azure AD and provide the necessary details in the   Azure AD Service Account Configuration   section     1  Provide the   Client ID   of your Azure AD application     1  Provide the   Client Secret   of your Azure AD application  the   Client Secret   will be used to request an access token from Azure AD     1  Provide the Azure AD request   Access Token URL       1  If you don t have users with more than 150 groups  you can still force the use of the Graph API by enabling the   Force use Graph API   toggle  1  If you have multiple organizations and want to automatically add users to organizations  complete the   Org mapping section        First  you need to configure the   Org attribute   field to specify which SAML attribute should be used to retrieve SAML organization information     Now fill in the   Org mapping   field with mappings from SAML organization to Grafana organization  For example   Org mapping  Engineering 2  Sales 2  will map users who belong to  Engineering  or  Sales  organizations in SAML to Grafana organization with ID 2     If you want users to have different roles in different organizations  you can additionally specify a role  For example   Org mapping  Engineering 2 Editor  will map users who belong to  Engineering  organizations in SAML to Grafana organization with ID 2 and assign them Editor role      Organization mapping will automatically update user s organization memberships  and roles  if they have been configured  based on their SAML organization every time the user logs in to Grafana     Learn more about  SAML organization mapping      1  If you want to limit the access to Grafana based on user s SAML organization membership  fill in the   Allowed organizations   field  1  Click   Next  Test and enable         5  Test And Enable Section  1  Click   Save and enable        If there are issues with your configuration  an error message will appear  Refer back to the previous steps to correct the issues and click on  Save and apply  on the top right corner once you are done  1  If there are no configuration issues  SAML integration status will change to  Enabled      Your SAML configuration is now enabled  1  To disable SAML integration  click  Disable  in the top right corner


grafana setup documentation labels auth gitlab aliases keywords configuration grafana Grafana GitLab OAuth Guide oauth

Answer:
---
aliases:
  - ../../../auth/gitlab/
description: Grafana GitLab OAuth Guide
keywords:
  - grafana
  - configuration
  - documentation
  - oauth
labels:
  products:
    - cloud
    - enterprise
    - oss
menuTitle: GitLab OAuth
title: Configure GitLab OAuth authentication
weight: 1000
---

# Configure GitLab OAuth authentication

This topic describes how to configure GitLab OAuth authentication.

If Users use the same email address in GitLab that they use with other authentication providers (such as Grafana.com), you need to do additional configuration to ensure that the users are matched correctly. Please refer to the [Using the same email address to login with different identity providers]() documentation for more information.

## Before you begin

Ensure you know how to create a GitLab OAuth application. Consult GitLab's documentation on [creating a GitLab OAuth application](https://docs.gitlab.com/ee/integration/oauth_provider.html) for more information.

### Create a GitLab OAuth Application

1. Log in to your GitLab account and go to **Profile > Preferences > Applications**.
1. Click **Add new application**.
1. Fill out the fields.
   - In the **Redirect URI** field, enter the following: `https://<YOUR-GRAFANA-URL>/login/gitlab` and check `openid`, `email`, `profile` in the **Scopes** list.
   - Leave the **Confidential** checkbox checked.
1. Click **Save application**.
1. Note your **Application ID** (this is the `Client Id`) and **Secret** (this is the `Client Secret`).

## Configure GitLab authentication client using the Grafana UI

Available in Public Preview in Grafana 10.4 behind the `ssoSettingsApi` feature toggle.

As a Grafana Admin, you can configure GitLab OAuth client from within Grafana using the GitLab UI. To do this, navigate to **Administration > Authentication > GitLab** page and fill in the form. If you have a current configuration in the Grafana configuration file then the form will be pre-populated with those values otherwise the form will contain default values.

After you have filled in the form, click **Save** to save the configuration. If the save was successful, Grafana will apply the new configurations.

If you need to reset changes you made in the UI back to the default values, click **Reset**. After you have reset the changes, Grafana will apply the configuration from the Grafana configuration file (if there is any configuration) or the default values.

If you run Grafana in high availability mode, configuration changes may not get applied to all Grafana instances immediately. You may need to wait a few minutes for the configuration to propagate to all Grafana instances.

Refer to [configuration options]() for more information.

## Configure GitLab authentication client using the Terraform provider

Available in Public Preview in Grafana 10.4 behind the `ssoSettingsApi` feature toggle. Supported in the Terraform provider since v2.12.0.

```terraform
resource "grafana_sso_settings" "gitlab_sso_settings" {
  provider_name = "gitlab"
  oauth2_settings {
    name                  = "Gitlab"
    client_id             = "YOUR_GITLAB_APPLICATION_ID"
    client_secret         = "YOUR_GITLAB_APPLICATION_SECRET"
    allow_sign_up         = true
    auto_login            = false
    scopes                = "openid email profile"
    allowed_domains       = "mycompany.com mycompany.org"
    role_attribute_path   = "contains(groups[*], 'example-group') && 'Editor' || 'Viewer'"
    role_attribute_strict = false
    allowed_groups        = "[\"admins\", \"software engineers\", \"developers/frontend\"]"
    use_pkce              = true
    use_refresh_token     = true
  }
}
```

Go to [Terraform Registry](https://registry.terraform.io/providers/grafana/grafana/latest/docs/resources/sso_settings) for a complete reference on using the `grafana_sso_settings` resource.

## Configure GitLab authentication client using the Grafana configuration file

Ensure that you have access to the [Grafana configuration file]().

### Steps

To configure GitLab authentication with Grafana, follow these steps:

1. Create an OAuth application in GitLab.

   1. Set the redirect URI to `http://<my_grafana_server_name_or_ip>:<grafana_server_port>/login/gitlab`.

      Ensure that the Redirect URI is the complete HTTP address that you use to access Grafana via your browser, but with the appended path of `/login/gitlab`.

      For the Redirect URI to be correct, it might be necessary to set the `root_url` option in the `[server]`section of the Grafana configuration file. For example, if you are serving Grafana behind a proxy.

   1. Set the OAuth2 scopes to `openid`, `email` and `profile`.

1. Refer to the following table to update field values located in the `[auth.gitlab]` section of the Grafana configuration file:

   | Field                        | Description                                                                                |
   | ---------------------------- | --------------------------------------------------------------------------------------------- |
   | `client_id`, `client_secret` | These values must match the `Application ID` and `Secret` from your GitLab OAuth application. |
   | `enabled`                    | Enables GitLab authentication. Set this value to `true`.                                      |

   Review the list of other GitLab [configuration options]() and complete them, as necessary.

1. Optional: [Configure a refresh token]():

   a. Set `use_refresh_token` to `true` in `[auth.gitlab]` section in Grafana configuration file.

1. [Configure role mapping]().
1. Optional: [Configure group synchronization]().
1. Restart Grafana.

   You should now see a GitLab login button on the login page and be able to log in or sign up with your GitLab accounts.

### Configure a refresh token

When a user logs in using an OAuth provider, Grafana verifies that the access token has not expired. When an access token expires, Grafana uses the provided refresh token (if any exists) to obtain a new access token.

Grafana uses a refresh token to obtain a new access token without requiring the user to log in again. If a refresh token doesn't exist, Grafana logs the user out of the system after the access token has expired.

By default, GitLab provides a refresh token.

Refresh token fetching and access token expiration check is enabled by default for the GitLab provider since Grafana v10.1.0. If you would like to disable access token expiration check then set the `use_refresh_token` configuration value to `false`.

The `accessTokenExpirationCheck` feature toggle has been removed in Grafana v10.3.0 and the `use_refresh_token` configuration value will be used instead for configuring refresh token fetching and access token expiration check.

### Configure allowed groups

To limit access to authenticated users that are members of one or more [GitLab
groups](https://docs.gitlab.com/ce/user/group/index.html), set `allowed_groups`
to a comma or space-separated list of groups.

GitLab's groups are referenced by the group name. For example, `developers`. To reference a subgroup `frontend`, use `developers/frontend`.
Note that in GitLab, the group or subgroup name does not always match its display name, especially if the display name contains spaces or special characters.
Make sure you always use the group or subgroup name as it appears in the URL of the group or subgroup.

### Configure role mapping

Unless `skip_org_role_sync` option is enabled, the user's role will be set to the role retrieved from GitLab upon user login.

The user's role is retrieved using a [JMESPath](http://jmespath.org/examples.html) expression from the `role_attribute_path` configuration option.
To map the server administrator role, use the `allow_assign_grafana_admin` configuration option.
Refer to [configuration options]() for more information.

You can use the `org_mapping` configuration option to assign the user to multiple organizations and specify their role based on their GitLab group membership. For more information, refer to [Org roles mapping example](#org-roles-mapping-example). If the org role mapping (`org_mapping`) is specified and Entra ID returns a valid role, then the user will get the highest of the two roles.

If no valid role is found, the user is assigned the role specified by [the `auto_assign_org_role` option]().
You can disable this default role assignment by setting `role_attribute_strict = true`. This setting denies user access if no role or an invalid role is returned after evaluating the `role_attribute_path` and the `org_mapping` expressions.

To ease configuration of a proper JMESPath expression, go to [JMESPath](http://jmespath.org/) to test and evaluate expressions with custom payloads.

### Role mapping examples

This section includes examples of JMESPath expressions used for role mapping.

##### Org roles mapping example

The GitLab integration uses the external users' groups in the `org_mapping` configuration to map organizations and roles based on their GitLab group membership.

In this example, the user has been granted the role of a `Viewer` in the `org_foo` organization, and the role of an `Editor` in the `org_bar` and `org_baz` orgs.

The external user is part of the following GitLab groups: `groupd-1` and `group-2`.

Config:

```ini
org_mapping = group-1:org_foo:Viewer groupd-1:org_bar:Editor *:org_baz:Editor
```

#### Map roles using user information from OAuth token

In this example, the user with email `admin@company.com` has been granted the `Admin` role.
All other users are granted the `Viewer` role.

```ini
role_attribute_path = email=='admin@company.com' && 'Admin' || 'Viewer'
```

#### Map roles using groups

In this example, the user from GitLab group 'example-group' have been granted the `Editor` role.
All other users are granted the `Viewer` role.

```ini
role_attribute_path = contains(groups[*], 'example-group') && 'Editor' || 'Viewer'
```

#### Map server administrator role

In this example, the user with email `admin@company.com` has been granted the `Admin` organization role as well as the Grafana server admin role.
All other users are granted the `Viewer` role.

```bash
role_attribute_path = email=='admin@company.com' && 'GrafanaAdmin' || 'Viewer'
```

#### Map one role to all users

In this example, all users will be assigned `Viewer` role regardless of the user information received from the identity provider.

```ini
role_attribute_path = "'Viewer'"
skip_org_role_sync = false
```

### Example of GitLab configuration in Grafana

This section includes an example of GitLab configuration in the Grafana configuration file.

```bash
[auth.gitlab]
enabled = true
allow_sign_up = true
auto_login = false
client_id = YOUR_GITLAB_APPLICATION_ID
client_secret = YOUR_GITLAB_APPLICATION_SECRET
scopes = openid email profile
auth_url = https://gitlab.com/oauth/authorize
token_url = https://gitlab.com/oauth/token
api_url = https://gitlab.com/api/v4
role_attribute_path = contains(groups[*], 'example-group') && 'Editor' || 'Viewer'
role_attribute_strict = false
allow_assign_grafana_admin = false
allowed_groups = ["admins", "software engineers", "developers/frontend"]
allowed_domains = mycompany.com mycompany.org
tls_skip_verify_insecure = false
use_pkce = true
use_refresh_token = true
```

## Configure group synchronization

Available in [Grafana Enterprise](https://grafana.com/docs/grafana/<GRAFANA_VERSION>/introduction/grafana-enterprise) and [Grafana Cloud](/docs/grafana-cloud/).

Grafana supports synchronization of GitLab groups with Grafana teams and roles. This allows automatically assigning users to the appropriate teams or granting them the mapped roles.
Teams and roles get synchronized when the user logs in.

GitLab groups are referenced by the group name. For example, `developers`. To reference a subgroup `frontend`, use `developers/frontend`.
Note that in GitLab, the group or subgroup name does not always match its display name, especially if the display name contains spaces or special characters.
Make sure you always use the group or subgroup name as it appears in the URL of the group or subgroup.

To learn more about group synchronization, refer to [Configure team sync](https://grafana.com/docs/grafana/<GRAFANA_VERSION>/setup-grafana/configure-security/configure-team-sync) and [Configure group attribute sync](https://grafana.com/docs/grafana/<GRAFANA_VERSION>/setup-grafana/configure-security/configure-group-attribute-sync).

## Configuration options

The table below describes all GitLab OAuth configuration options. You can apply these options as environment variables, similar to any other configuration within Grafana. For more information, refer to [Override configuration with environment variables]().

If the configuration option requires a JMESPath expression that includes a colon, enclose the entire expression in quotes to prevent parsing errors. For example `role_attribute_path: "role:view"`

| Setting                      | Required | Supported on Cloud | Description                                                                                | Default                              |
| ---------------------------- | -------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ |
| `enabled`                    | Yes      | Yes                | Whether GitLab OAuth authentication is allowed.                                                                                | `false`                              |
| `client_id`                  | Yes      | Yes                | Client ID provided by your GitLab OAuth app.                                                                                |                                      |
| `client_secret`              | Yes      | Yes                | Client secret provided by your GitLab OAuth app.                                                                                |                                      |
| `auth_url`                   | Yes      | Yes                | Authorization endpoint of your GitLab OAuth provider. If you use your own instance of GitLab instead of gitlab.com, adjust `auth_url` by replacing the `gitlab.com` hostname with your own.                                                                                | `https://gitlab.com/oauth/authorize` |
| `token_url`                  | Yes      | Yes                | Endpoint used to obtain GitLab OAuth access token. If you use your own instance of GitLab instead of gitlab.com, adjust `token_url` by replacing the `gitlab.com` hostname with your own.                                                                                | `https://gitlab.com/oauth/token`     |
| `api_url`                    | No       | Yes                | Grafana uses `<api_url>/user` endpoint to obtain GitLab user information compatible with [OpenID UserInfo](https://connect2id.com/products/server/docs/api/userinfo).                                                                                | `https://gitlab.com/api/v4`          |
| `name`                       | No       | Yes                | Name used to refer to the GitLab authentication in the Grafana user interface.                                                                                | `GitLab`                             |
| `icon`                       | No       | Yes                | Icon used for GitLab authentication in the Grafana user interface.                                                                                | `gitlab`                             |
| `scopes`                     | No       | Yes                | List of comma or space-separated GitLab OAuth scopes.                                                                                | `openid email profile`               |
| `allow_sign_up`              | No       | Yes                | Whether to allow new Grafana user creation through GitLab login. If set to `false`, then only existing Grafana users can log in with GitLab OAuth.                                                                                | `true`                               |
| `auto_login`                 | No       | Yes                | Set to `true` to enable users to bypass the login screen and automatically log in. This setting is ignored if you configure multiple auth providers to use auto-login.                                                                                | `false`                              |
| `role_attribute_path`        | No       | Yes                | [JMESPath](http://jmespath.org/examples.html) expression to use for Grafana role lookup. Grafana will first evaluate the expression using the GitLab OAuth token. If no role is found, Grafana creates a JSON data with `groups` key that maps to groups obtained from GitLab's `/oauth/userinfo` endpoint, and evaluates the expression using this data. Finally, if a valid role is still not found, the expression is evaluated against the user information retrieved from `api_url/users` endpoint and groups retrieved from `api_url/groups` endpoint. The result of the evaluation should be a valid Grafana role (`None`, `Viewer`, `Editor`, `Admin` or `GrafanaAdmin`). For more information on user role mapping, refer to [Configure role mapping](). |                                      |
| `role_attribute_strict`      | No       | Yes                | Set to `true` to deny user login if the Grafana role cannot be extracted using `role_attribute_path`. For more information on user role mapping, refer to [Configure role mapping]().                                                                                | `false`                              |
| `org_mapping`                | No       | No                 | List of comma- or space-separated `<ExternalGitlabGroupName>:<OrgIdOrName>:<Role>` mappings. Value can be `*` meaning "All users". Role is optional and can have the following values: `None`, `Viewer`, `Editor` or `Admin`. For more information on external organization to role mapping, refer to [Org roles mapping example](#org-roles-mapping-example).                                                                                |                                      |
| `skip_org_role_sync`         | No       | Yes                | Set to `true` to stop automatically syncing user roles.                                                                                | `false`                              |
| `allow_assign_grafana_admin` | No       | No                 | Set to `true` to enable automatic sync of the Grafana server administrator role. If this option is set to `true` and the result of evaluating `role_attribute_path` for a user is `GrafanaAdmin`, Grafana grants the user the server administrator privileges and organization administrator role. If this option is set to `false` and the result of evaluating `role_attribute_path` for a user is `GrafanaAdmin`, Grafana grants the user only organization administrator role. For more information on user role mapping, refer to [Configure role mapping]().                                                                                | `false`                              |
| `allowed_domains`            | No       | Yes                | List of comma or space-separated domains. User must belong to at least one domain to log in.                                                                                |                                      |
| `allowed_groups`             | No       | Yes                | List of comma or space-separated groups. The user should be a member of at least one group to log in.                                                                                |                                      |
| `tls_skip_verify_insecure`   | No       | No                 | If set to `true`, the client accepts any certificate presented by the server and any host name in that certificate. _You should only use this for testing_, because this mode leaves SSL/TLS susceptible to man-in-the-middle attacks.                                                                                | `false`                              |
| `tls_client_cert`            | No       | No                 | The path to the certificate.                                                                                |                                      |
| `tls_client_key`             | No       | No                 | The path to the key.                                                                                |                                      |
| `tls_client_ca`              | No       | No                 | The path to the trusted certificate authority list.                                                                                |                                      |
| `use_pkce`                   | No       | Yes                | Set to `true` to use [Proof Key for Code Exchange (PKCE)](https://datatracker.ietf.org/doc/html/rfc7636). Grafana uses the SHA256 based `S256` challenge method and a 128 bytes (base64url encoded) code verifier.                                                                                | `true`                               |
| `use_refresh_token`          | No       | Yes                | Set to `true` to use refresh token and check access token expiration. The `accessTokenExpirationCheck` feature toggle should also be enabled to use refresh token.                                                                                | `true`                               |
| `signout_redirect_url`       | No       | Yes                | URL to redirect to after the user logs out.                                                                                |                                      |

aliases               auth gitlab  description  Grafana GitLab OAuth Guide keywords      grafana     configuration     documentation     oauth labels    products        cloud       enterprise       oss menuTitle  GitLab OAuth title  Configure GitLab OAuth authentication weight  1000        Configure GitLab OAuth authentication    This topic describes how to configure GitLab OAuth authentication    If Users use the same email address in GitLab that they use with other authentication providers  such as Grafana com   you need to do additional configuration to ensure that the users are matched correctly  Please refer to the  Using the same email address to login with different identity providers    documentation for more information       Before you begin  Ensure you know how to create a GitLab OAuth application  Consult GitLab s documentation on  creating a GitLab OAuth application  https   docs gitlab com ee integration oauth provider html  for more information       Create a GitLab OAuth Application  1  Log in to your GitLab account and go to   Profile   Preferences   Applications    1  Click   Add new application    1  Fill out the fields       In the   Redirect URI   field  enter the following   https    YOUR GRAFANA URL  login gitlab  and check  openid    email    profile  in the   Scopes   list       Leave the   Confidential   checkbox checked  1  Click   Save application    1  Note your   Application ID    this is the  Client Id   and   Secret    this is the  Client Secret        Configure GitLab authentication client using the Grafana UI   Available in Public Preview in Grafana 10 4 behind the  ssoSettingsApi  feature toggle    As a Grafana Admin  you can configure GitLab OAuth client from within Grafana using the GitLab UI  To do this  navigate to   Administration   Authentication   GitLab   page and fill in the form  If you have a current configuration in the Grafana configuration file then the form will be pre populated with those values otherwise the form will contain default values   After you have filled in the form  click   Save   to save the configuration  If the save was successful  Grafana will apply the new configurations   If you need to reset changes you made in the UI back to the default values  click   Reset    After you have reset the changes  Grafana will apply the configuration from the Grafana configuration file  if there is any configuration  or the default values    If you run Grafana in high availability mode  configuration changes may not get applied to all Grafana instances immediately  You may need to wait a few minutes for the configuration to propagate to all Grafana instances    Refer to  configuration options    for more information      Configure GitLab authentication client using the Terraform provider   Available in Public Preview in Grafana 10 4 behind the  ssoSettingsApi  feature toggle  Supported in the Terraform provider since v2 12 0       terraform resource  grafana sso settings   gitlab sso settings      provider name    gitlab    oauth2 settings       name                     Gitlab      client id                YOUR GITLAB APPLICATION ID      client secret            YOUR GITLAB APPLICATION SECRET      allow sign up           true     auto login              false     scopes                   openid email profile      allowed domains          mycompany com mycompany org      role attribute path      contains groups      example group       Editor      Viewer       role attribute strict   false     allowed groups              admins      software engineers      developers frontend         use pkce                true     use refresh token       true            Go to  Terraform Registry  https   registry terraform io providers grafana grafana latest docs resources sso settings  for a complete reference on using the  grafana sso settings  resource      Configure GitLab authentication client using the Grafana configuration file  Ensure that you have access to the  Grafana configuration file          Steps  To configure GitLab authentication with Grafana  follow these steps   1  Create an OAuth application in GitLab      1  Set the redirect URI to  http    my grafana server name or ip   grafana server port  login gitlab          Ensure that the Redirect URI is the complete HTTP address that you use to access Grafana via your browser  but with the appended path of   login gitlab          For the Redirect URI to be correct  it might be necessary to set the  root url  option in the   server  section of the Grafana configuration file  For example  if you are serving Grafana behind a proxy      1  Set the OAuth2 scopes to  openid    email  and  profile    1  Refer to the following table to update field values located in the   auth gitlab   section of the Grafana configuration file        Field                          Description                                                                                client id    client secret    These values must match the  Application ID  and  Secret  from your GitLab OAuth application          enabled                       Enables GitLab authentication  Set this value to  true                                              Review the list of other GitLab  configuration options    and complete them  as necessary   1  Optional   Configure a refresh token         a  Set  use refresh token  to  true  in   auth gitlab   section in Grafana configuration file   1   Configure role mapping     1  Optional   Configure group synchronization     1  Restart Grafana      You should now see a GitLab login button on the login page and be able to log in or sign up with your GitLab accounts       Configure a refresh token  When a user logs in using an OAuth provider  Grafana verifies that the access token has not expired  When an access token expires  Grafana uses the provided refresh token  if any exists  to obtain a new access token   Grafana uses a refresh token to obtain a new access token without requiring the user to log in again  If a refresh token doesn t exist  Grafana logs the user out of the system after the access token has expired   By default  GitLab provides a refresh token   Refresh token fetching and access token expiration check is enabled by default for the GitLab provider since Grafana v10 1 0  If you would like to disable access token expiration check then set the  use refresh token  configuration value to  false     The  accessTokenExpirationCheck  feature toggle has been removed in Grafana v10 3 0 and the  use refresh token  configuration value will be used instead for configuring refresh token fetching and access token expiration check        Configure allowed groups  To limit access to authenticated users that are members of one or more  GitLab groups  https   docs gitlab com ce user group index html   set  allowed groups  to a comma or space separated list of groups   GitLab s groups are referenced by the group name  For example   developers   To reference a subgroup  frontend   use  developers frontend   Note that in GitLab  the group or subgroup name does not always match its display name  especially if the display name contains spaces or special characters  Make sure you always use the group or subgroup name as it appears in the URL of the group or subgroup       Configure role mapping  Unless  skip org role sync  option is enabled  the user s role will be set to the role retrieved from GitLab upon user login   The user s role is retrieved using a  JMESPath  http   jmespath org examples html  expression from the  role attribute path  configuration option  To map the server administrator role  use the  allow assign grafana admin  configuration option  Refer to  configuration options    for more information   You can use the  org mapping  configuration option to assign the user to multiple organizations and specify their role based on their GitLab group membership  For more information  refer to  Org roles mapping example   org roles mapping example   If the org role mapping   org mapping   is specified and Entra ID returns a valid role  then the user will get the highest of the two roles   If no valid role is found  the user is assigned the role specified by  the  auto assign org role  option     You can disable this default role assignment by setting  role attribute strict   true   This setting denies user access if no role or an invalid role is returned after evaluating the  role attribute path  and the  org mapping  expressions   To ease configuration of a proper JMESPath expression  go to  JMESPath  http   jmespath org   to test and evaluate expressions with custom payloads       Role mapping examples  This section includes examples of JMESPath expressions used for role mapping         Org roles mapping example  The GitLab integration uses the external users  groups in the  org mapping  configuration to map organizations and roles based on their GitLab group membership   In this example  the user has been granted the role of a  Viewer  in the  org foo  organization  and the role of an  Editor  in the  org bar  and  org baz  orgs   The external user is part of the following GitLab groups   groupd 1  and  group 2    Config      ini org mapping   group 1 org foo Viewer groupd 1 org bar Editor   org baz Editor           Map roles using user information from OAuth token  In this example  the user with email  admin company com  has been granted the  Admin  role  All other users are granted the  Viewer  role      ini role attribute path   email   admin company com      Admin      Viewer            Map roles using groups  In this example  the user from GitLab group  example group  have been granted the  Editor  role  All other users are granted the  Viewer  role      ini role attribute path   contains groups      example group       Editor      Viewer            Map server administrator role  In this example  the user with email  admin company com  has been granted the  Admin  organization role as well as the Grafana server admin role  All other users are granted the  Viewer  role      bash role attribute path   email   admin company com      GrafanaAdmin      Viewer            Map one role to all users  In this example  all users will be assigned  Viewer  role regardless of the user information received from the identity provider      ini role attribute path     Viewer   skip org role sync   false          Example of GitLab configuration in Grafana  This section includes an example of GitLab configuration in the Grafana configuration file      bash  auth gitlab  enabled   true allow sign up   true auto login   false client id   YOUR GITLAB APPLICATION ID client secret   YOUR GITLAB APPLICATION SECRET scopes   openid email profile auth url   https   gitlab com oauth authorize token url   https   gitlab com oauth token api url   https   gitlab com api v4 role attribute path   contains groups      example group       Editor      Viewer  role attribute strict   false allow assign grafana admin   false allowed groups     admins    software engineers    developers frontend   allowed domains   mycompany com mycompany org tls skip verify insecure   false use pkce   true use refresh token   true         Configure group synchronization   Available in  Grafana Enterprise  https   grafana com docs grafana  GRAFANA VERSION  introduction grafana enterprise  and  Grafana Cloud   docs grafana cloud      Grafana supports synchronization of GitLab groups with Grafana teams and roles  This allows automatically assigning users to the appropriate teams or granting them the mapped roles  Teams and roles get synchronized when the user logs in   GitLab groups are referenced by the group name  For example   developers   To reference a subgroup  frontend   use  developers frontend   Note that in GitLab  the group or subgroup name does not always match its display name  especially if the display name contains spaces or special characters  Make sure you always use the group or subgroup name as it appears in the URL of the group or subgroup   To learn more about group synchronization  refer to  Configure team sync  https   grafana com docs grafana  GRAFANA VERSION  setup grafana configure security configure team sync  and  Configure group attribute sync  https   grafana com docs grafana  GRAFANA VERSION  setup grafana configure security configure group attribute sync       Configuration options  The table below describes all GitLab OAuth configuration options  You can apply these options as environment variables  similar to any other configuration within Grafana  For more information  refer to  Override configuration with environment variables       If the configuration option requires a JMESPath expression that includes a colon  enclose the entire expression in quotes to prevent parsing errors  For example  role attribute path   role view       Setting                        Required   Supported on Cloud   Description                                                                                Default                                                                                enabled                       Yes        Yes                  Whether GitLab OAuth authentication is allowed                                                                                false                                    client id                     Yes        Yes                  Client ID provided by your GitLab OAuth app                                                                                client secret                 Yes        Yes                  Client secret provided by your GitLab OAuth app                                                                                auth url                      Yes        Yes                  Authorization endpoint of your GitLab OAuth provider  If you use your own instance of GitLab instead of gitlab com  adjust  auth url  by replacing the  gitlab com  hostname with your own                                                                                https   gitlab com oauth authorize       token url                     Yes        Yes                  Endpoint used to obtain GitLab OAuth access token  If you use your own instance of GitLab instead of gitlab com  adjust  token url  by replacing the  gitlab com  hostname with your own                                                                                https   gitlab com oauth token           api url                       No         Yes                  Grafana uses   api url  user  endpoint to obtain GitLab user information compatible with  OpenID UserInfo  https   connect2id com products server docs api userinfo                                                                                https   gitlab com api v4                name                          No         Yes                  Name used to refer to the GitLab authentication in the Grafana user interface                                                                                GitLab                                   icon                          No         Yes                  Icon used for GitLab authentication in the Grafana user interface                                                                                gitlab                                   scopes                        No         Yes                  List of comma or space separated GitLab OAuth scopes                                                                                openid email profile                     allow sign up                 No         Yes                  Whether to allow new Grafana user creation through GitLab login  If set to  false   then only existing Grafana users can log in with GitLab OAuth                                                                                true                                     auto login                    No         Yes                  Set to  true  to enable users to bypass the login screen and automatically log in  This setting is ignored if you configure multiple auth providers to use auto login                                                                                false                                    role attribute path           No         Yes                   JMESPath  http   jmespath org examples html  expression to use for Grafana role lookup  Grafana will first evaluate the expression using the GitLab OAuth token  If no role is found  Grafana creates a JSON data with  groups  key that maps to groups obtained from GitLab s   oauth userinfo  endpoint  and evaluates the expression using this data  Finally  if a valid role is still not found  the expression is evaluated against the user information retrieved from  api url users  endpoint and groups retrieved from  api url groups  endpoint  The result of the evaluation should be a valid Grafana role   None    Viewer    Editor    Admin  or  GrafanaAdmin    For more information on user role mapping  refer to  Configure role mapping                                                 role attribute strict         No         Yes                  Set to  true  to deny user login if the Grafana role cannot be extracted using  role attribute path   For more information on user role mapping  refer to  Configure role mapping                                                                                false                                    org mapping                   No         No                   List of comma  or space separated   ExternalGitlabGroupName   OrgIdOrName   Role   mappings  Value can be     meaning  All users   Role is optional and can have the following values   None    Viewer    Editor  or  Admin   For more information on external organization to role mapping  refer to  Org roles mapping example   org roles mapping example                                                                                skip org role sync            No         Yes                  Set to  true  to stop automatically syncing user roles                                                                                false                                    allow assign grafana admin    No         No                   Set to  true  to enable automatic sync of the Grafana server administrator role  If this option is set to  true  and the result of evaluating  role attribute path  for a user is  GrafanaAdmin   Grafana grants the user the server administrator privileges and organization administrator role  If this option is set to  false  and the result of evaluating  role attribute path  for a user is  GrafanaAdmin   Grafana grants the user only organization administrator role  For more information on user role mapping  refer to  Configure role mapping                                                                                false                                    allowed domains               No         Yes                  List of comma or space separated domains  User must belong to at least one domain to log in                                                                                allowed groups                No         Yes                  List of comma or space separated groups  The user should be a member of at least one group to log in                                                                                tls skip verify insecure      No         No                   If set to  true   the client accepts any certificate presented by the server and any host name in that certificate   You should only use this for testing   because this mode leaves SSL TLS susceptible to man in the middle attacks                                                                                false                                    tls client cert               No         No                   The path to the certificate                                                                                tls client key                No         No                   The path to the key                                                                                tls client ca                 No         No                   The path to the trusted certificate authority list                                                                                use pkce                      No         Yes                  Set to  true  to use  Proof Key for Code Exchange  PKCE   https   datatracker ietf org doc html rfc7636   Grafana uses the SHA256 based  S256  challenge method and a 128 bytes  base64url encoded  code verifier                                                                                true                                     use refresh token             No         Yes                  Set to  true  to use refresh token and check access token expiration  The  accessTokenExpirationCheck  feature toggle should also be enabled to use refresh token                                                                                true                                     signout redirect url          No         Yes                  URL to redirect to after the user logs out


grafana setup documentation Grafana Auth Proxy Guide aliases tutorials authproxy proxy auth auth proxy keywords configuration grafana

Answer:
---
aliases:
  - ../../../auth/auth-proxy/
  - ../../../tutorials/authproxy/
description: Grafana Auth Proxy Guide
keywords:
  - grafana
  - configuration
  - documentation
  - proxy
labels:
  products:
    - cloud
    - enterprise
    - oss
menuTitle: Auth proxy
title: Configure auth proxy authentication
weight: 1500
---

# Configure auth proxy authentication

You can configure Grafana to let a HTTP reverse proxy handle authentication. Popular web servers have a very
extensive list of pluggable authentication modules, and any of them can be used with the AuthProxy feature.
Below we detail the configuration options for auth proxy.

```bash
[auth.proxy]
# Defaults to false, but set to true to enable this feature
enabled = true
# HTTP Header name that will contain the username or email
header_name = X-WEBAUTH-USER
# HTTP Header property, defaults to `username` but can also be `email`
header_property = username
# Set to `true` to enable auto sign up of users who do not exist in Grafana DB. Defaults to `true`.
auto_sign_up = true
# Define cache time to live in minutes
# If combined with Grafana LDAP integration it is also the sync interval
# Set to 0 to always fetch and sync the latest user data
sync_ttl = 15
# Limit where auth proxy requests come from by configuring a list of IP addresses.
# This can be used to prevent users spoofing the X-WEBAUTH-USER header.
# Example `whitelist = 192.168.1.1, 192.168.1.0/24, 2001::23, 2001::0/120`
whitelist =
# Optionally define more headers to sync other user attributes
# Example `headers = Name:X-WEBAUTH-NAME Role:X-WEBAUTH-ROLE Email:X-WEBAUTH-EMAIL Groups:X-WEBAUTH-GROUPS`
headers =
# Non-ASCII strings in header values are encoded using quoted-printable encoding
;headers_encoded = false
# Check out docs on this for more details on the below setting
enable_login_token = false
```

## Interacting with Grafana’s AuthProxy via curl

```bash
curl -H "X-WEBAUTH-USER: admin"  http://localhost:3000/api/users
[
    {
        "id":1,
        "name":"",
        "login":"admin",
        "email":"admin@localhost",
        "isAdmin":true
    }
]
```

We can then send a second request to the `/api/user` method which will return the details of the logged in user. We will use this request to show how Grafana automatically adds the new user we specify to the system. Here we create a new user called “anthony”.

```bash
curl -H "X-WEBAUTH-USER: anthony" http://localhost:3000/api/user
{
    "email":"anthony",
    "name":"",
    "login":"anthony",
    "theme":"",
    "orgId":1,
    "isGrafanaAdmin":false
}
```

## Making Apache’s auth work together with Grafana’s AuthProxy

I’ll demonstrate how to use Apache for authenticating users. In this example we use BasicAuth with Apache’s text file based authentication handler, i.e. htpasswd files. However, any available Apache authentication capabilities could be used.

### Apache BasicAuth

In this example we use Apache as a reverse proxy in front of Grafana. Apache handles the Authentication of users before forwarding requests to the Grafana backend service.

#### Apache configuration

```bash
    <VirtualHost *:80>
        ServerAdmin webmaster@authproxy
        ServerName authproxy
        ErrorLog "logs/authproxy-error_log"
        CustomLog "logs/authproxy-access_log" common

        <Proxy *>
            AuthType Basic
            AuthName GrafanaAuthProxy
            AuthBasicProvider file
            AuthUserFile /etc/apache2/grafana_htpasswd
            Require valid-user

            RewriteEngine On
            RewriteRule .* - [E=PROXY_USER:%{LA-U:REMOTE_USER},NS]
            RequestHeader set X-WEBAUTH-USER "%{PROXY_USER}e"
        </Proxy>

        RequestHeader unset Authorization

        ProxyRequests Off
        ProxyPass / http://localhost:3000/
        ProxyPassReverse / http://localhost:3000/
    </VirtualHost>
```

- The first four lines of the virtualhost configuration are standard, so we won’t go into detail on what they do.

- We use a **\<proxy>** configuration block for applying our authentication rules to every proxied request. These rules include requiring basic authentication where user:password credentials are stored in the **/etc/apache2/grafana_htpasswd** file. This file can be created with the `htpasswd` command.

  - The next part of the configuration is the tricky part. We use Apache’s rewrite engine to create our **X-WEBAUTH-USER header**, populated with the authenticated user.

    - **RewriteRule .\* - [E=PROXY_USER:%{LA-U:REMOTE_USER}, NS]**: This line is a little bit of magic. What it does, is for every request use the rewriteEngines look-ahead (LA-U) feature to determine what the REMOTE_USER variable would be set to after processing the request. Then assign the result to the variable PROXY_USER. This is necessary as the REMOTE_USER variable is not available to the RequestHeader function.

    - **RequestHeader set X-WEBAUTH-USER “%{PROXY_USER}e”**: With the authenticated username now stored in the PROXY_USER variable, we create a new HTTP request header that will be sent to our backend Grafana containing the username.

- The **RequestHeader unset Authorization** removes the Authorization header from the HTTP request before it is forwarded to Grafana. This ensures that Grafana does not try to authenticate the user using these credentials (BasicAuth is a supported authentication handler in Grafana).

- The last 3 lines are then just standard reverse proxy configuration to direct all authenticated requests to our Grafana server running on port 3000.

## Full walkthrough using Docker.

For this example, we use the official Grafana Docker image available at [Docker Hub](https://hub.docker.com/r/grafana/grafana/).

- Create a file `grafana.ini` with the following contents

```bash
[users]
allow_sign_up = false
auto_assign_org = true
auto_assign_org_role = Editor

[auth.proxy]
enabled = true
header_name = X-WEBAUTH-USER
header_property = username
auto_sign_up = true
```

Launch the Grafana container, using our custom grafana.ini to replace `/etc/grafana/grafana.ini`. We don't expose
any ports for this container as it will only be connected to by our Apache container.

```bash
docker run -i -v $(pwd)/grafana.ini:/etc/grafana/grafana.ini --name grafana grafana/grafana
```

### Apache Container

For this example we use the official Apache docker image available at [Docker Hub](https://hub.docker.com/_/httpd/)

- Create a file `httpd.conf` with the following contents

```bash
ServerRoot "/usr/local/apache2"
Listen 80
LoadModule mpm_event_module modules/mod_mpm_event.so
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_core_module modules/mod_authn_core.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_core_module modules/mod_authz_core.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule env_module modules/mod_env.so
LoadModule headers_module modules/mod_headers.so
LoadModule unixd_module modules/mod_unixd.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
<IfModule unixd_module>
User daemon
Group daemon
</IfModule>
ServerAdmin you@example.com
<Directory />
    AllowOverride none
    Require all denied
</Directory>
DocumentRoot "/usr/local/apache2/htdocs"
ErrorLog /proc/self/fd/2
LogLevel error
<IfModule log_config_module>
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common
    <IfModule logio_module>
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>
    CustomLog /proc/self/fd/1 common
</IfModule>
<Proxy *>
    AuthType Basic
    AuthName GrafanaAuthProxy
    AuthBasicProvider file
    AuthUserFile /tmp/htpasswd
    Require valid-user
    RewriteEngine On
    RewriteRule .* - [E=PROXY_USER:%{LA-U:REMOTE_USER},NS]
    RequestHeader set X-WEBAUTH-USER "%{PROXY_USER}e"
</Proxy>
RequestHeader unset Authorization
ProxyRequests Off
ProxyPass / http://grafana:3000/
ProxyPassReverse / http://grafana:3000/
```

- Create a htpasswd file. We create a new user **anthony** with the password **password**

  ```bash
  htpasswd -bc htpasswd anthony password
  ```

- Launch the httpd container using our custom httpd.conf and our htpasswd file. The container will listen on port 80, and we create a link to the **grafana** container so that this container can resolve the hostname **grafana** to the Grafana container’s IP address.

  ```bash
  docker run -i -p 80:80 --link grafana:grafana -v $(pwd)/httpd.conf:/usr/local/apache2/conf/httpd.conf -v $(pwd)/htpasswd:/tmp/htpasswd httpd:2.4
  ```

### Use grafana.

With our Grafana and Apache containers running, you can now connect to http://localhost/ and log in using the username/password we created in the htpasswd file.

If the user is deleted from Grafana, the user will be not be able to login and resync until after the `sync_ttl` has expired.

### Team Sync (Enterprise only)

> Only available in Grafana Enterprise v6.3+

With Team Sync, it's possible to set up synchronization between teams in your authentication provider and Grafana. You can send Grafana values as part of an HTTP header and have Grafana map them to your team structure. This allows you to put users into specific teams automatically.

To support the feature, auth proxy allows optional headers to map additional user attributes. The specific attribute to support team sync is `Groups`.

```bash
# Optionally define more headers to sync other user attributes
headers = "Groups:X-WEBAUTH-GROUPS"
```

You use the `X-WEBAUTH-GROUPS` header to send the team information for each user. Specifically, the set of Grafana's group IDs that the user belongs to.

First, we need to set up the mapping between your authentication provider and Grafana. Follow [these instructions]() to add groups to a team within Grafana.

Once that's done. You can verify your mappings by querying the API.

```bash
# First, inspect your teams and obtain the corresponding ID of the team we want to inspect the groups for.
curl -H "X-WEBAUTH-USER: admin" -H "X-WEBAUTH-GROUPS: lokiteamOnExternalSystem" http://localhost:3000/api/teams/search
{
  "totalCount": 2,
  "teams": [
    {
      "id": 1,
      "orgId": 1,
      "name": "Core",
      "email": "core@grafana.com",
      "avatarUrl": "/avatar/327a5353552d2dc3966e2e646908f540",
      "memberCount": 1,
      "permission": 0
    },
    {
      "id": 2,
      "orgId": 1,
      "name": "Loki",
      "email": "loki@grafana.com",
      "avatarUrl": "/avatar/102f937d5344d33fdb37b65d430f36ef",
      "memberCount": 0,
      "permission": 0
    }
  ],
  "page": 1,
  "perPage": 1000
}

# Then, query the groups for that particular team. In our case, the Loki team which has an ID of "2".
curl -H "X-WEBAUTH-USER: admin" -H "X-WEBAUTH-GROUPS: lokiteamOnExternalSystem" http://localhost:3000/api/teams/2/groups
[
  {
    "orgId": 1,
    "teamId": 2,
    "groupId": "lokiTeamOnExternalSystem"
  }
]
```

Finally, whenever Grafana receives a request with a header of `X-WEBAUTH-GROUPS: lokiTeamOnExternalSystem`, the user under authentication will be placed into the specified team. Placement in multiple teams is supported by using comma-separated values e.g. `lokiTeamOnExternalSystem,CoreTeamOnExternalSystem`.

```bash
curl -H "X-WEBAUTH-USER: leonard" -H "X-WEBAUTH-GROUPS: lokiteamOnExternalSystem" http://localhost:3000/dashboards/home
{
  "meta": {
    "isHome": true,
    "canSave": false,
    ...
}
```

With this, the user `leonard` will be automatically placed into the Loki team as part of Grafana authentication.

An empty `X-WEBAUTH-GROUPS` or the absence of a groups header will remove the user from all teams.

[Learn more about Team Sync]()

## Login token and session cookie

With `enable_login_token` set to `true` Grafana will, after successful auth proxy header validation, assign the user
a login token and cookie. You only have to configure your auth proxy to provide headers for the /login route.
Requests via other routes will be authenticated using the cookie.

Use settings `login_maximum_inactive_lifetime_duration` and `login_maximum_lifetime_duration` under `[auth]` to control session
lifetime.

aliases               auth auth proxy               tutorials authproxy  description  Grafana Auth Proxy Guide keywords      grafana     configuration     documentation     proxy labels    products        cloud       enterprise       oss menuTitle  Auth proxy title  Configure auth proxy authentication weight  1500        Configure auth proxy authentication  You can configure Grafana to let a HTTP reverse proxy handle authentication  Popular web servers have a very extensive list of pluggable authentication modules  and any of them can be used with the AuthProxy feature  Below we detail the configuration options for auth proxy      bash  auth proxy    Defaults to false  but set to true to enable this feature enabled   true   HTTP Header name that will contain the username or email header name   X WEBAUTH USER   HTTP Header property  defaults to  username  but can also be  email  header property   username   Set to  true  to enable auto sign up of users who do not exist in Grafana DB  Defaults to  true   auto sign up   true   Define cache time to live in minutes   If combined with Grafana LDAP integration it is also the sync interval   Set to 0 to always fetch and sync the latest user data sync ttl   15   Limit where auth proxy requests come from by configuring a list of IP addresses    This can be used to prevent users spoofing the X WEBAUTH USER header    Example  whitelist   192 168 1 1  192 168 1 0 24  2001  23  2001  0 120  whitelist     Optionally define more headers to sync other user attributes   Example  headers   Name X WEBAUTH NAME Role X WEBAUTH ROLE Email X WEBAUTH EMAIL Groups X WEBAUTH GROUPS  headers     Non ASCII strings in header values are encoded using quoted printable encoding  headers encoded   false   Check out docs on this for more details on the below setting enable login token   false         Interacting with Grafana s AuthProxy via curl     bash curl  H  X WEBAUTH USER  admin   http   localhost 3000 api users                  id  1           name               login   admin            email   admin localhost            isAdmin  true              We can then send a second request to the   api user  method which will return the details of the logged in user  We will use this request to show how Grafana automatically adds the new user we specify to the system  Here we create a new user called  anthony       bash curl  H  X WEBAUTH USER  anthony  http   localhost 3000 api user        email   anthony        name           login   anthony        theme           orgId  1       isGrafanaAdmin  false           Making Apache s auth work together with Grafana s AuthProxy  I ll demonstrate how to use Apache for authenticating users  In this example we use BasicAuth with Apache s text file based authentication handler  i e  htpasswd files  However  any available Apache authentication capabilities could be used       Apache BasicAuth  In this example we use Apache as a reverse proxy in front of Grafana  Apache handles the Authentication of users before forwarding requests to the Grafana backend service        Apache configuration     bash      VirtualHost   80          ServerAdmin webmaster authproxy         ServerName authproxy         ErrorLog  logs authproxy error log          CustomLog  logs authproxy access log  common           Proxy                AuthType Basic             AuthName GrafanaAuthProxy             AuthBasicProvider file             AuthUserFile  etc apache2 grafana htpasswd             Require valid user              RewriteEngine On             RewriteRule       E PROXY USER   LA U REMOTE USER  NS              RequestHeader set X WEBAUTH USER    PROXY USER e            Proxy           RequestHeader unset Authorization          ProxyRequests Off         ProxyPass   http   localhost 3000          ProxyPassReverse   http   localhost 3000        VirtualHost         The first four lines of the virtualhost configuration are standard  so we won t go into detail on what they do     We use a     proxy    configuration block for applying our authentication rules to every proxied request  These rules include requiring basic authentication where user password credentials are stored in the    etc apache2 grafana htpasswd   file  This file can be created with the  htpasswd  command       The next part of the configuration is the tricky part  We use Apache s rewrite engine to create our   X WEBAUTH USER header    populated with the authenticated user           RewriteRule        E PROXY USER   LA U REMOTE USER   NS     This line is a little bit of magic  What it does  is for every request use the rewriteEngines look ahead  LA U  feature to determine what the REMOTE USER variable would be set to after processing the request  Then assign the result to the variable PROXY USER  This is necessary as the REMOTE USER variable is not available to the RequestHeader function           RequestHeader set X WEBAUTH USER    PROXY USER e     With the authenticated username now stored in the PROXY USER variable  we create a new HTTP request header that will be sent to our backend Grafana containing the username     The   RequestHeader unset Authorization   removes the Authorization header from the HTTP request before it is forwarded to Grafana  This ensures that Grafana does not try to authenticate the user using these credentials  BasicAuth is a supported authentication handler in Grafana      The last 3 lines are then just standard reverse proxy configuration to direct all authenticated requests to our Grafana server running on port 3000      Full walkthrough using Docker   For this example  we use the official Grafana Docker image available at  Docker Hub  https   hub docker com r grafana grafana       Create a file  grafana ini  with the following contents     bash  users  allow sign up   false auto assign org   true auto assign org role   Editor   auth proxy  enabled   true header name   X WEBAUTH USER header property   username auto sign up   true      Launch the Grafana container  using our custom grafana ini to replace   etc grafana grafana ini   We don t expose any ports for this container as it will only be connected to by our Apache container      bash docker run  i  v   pwd  grafana ini  etc grafana grafana ini   name grafana grafana grafana          Apache Container  For this example we use the official Apache docker image available at  Docker Hub  https   hub docker com   httpd      Create a file  httpd conf  with the following contents     bash ServerRoot   usr local apache2  Listen 80 LoadModule mpm event module modules mod mpm event so LoadModule authn file module modules mod authn file so LoadModule authn core module modules mod authn core so LoadModule authz host module modules mod authz host so LoadModule authz user module modules mod authz user so LoadModule authz core module modules mod authz core so LoadModule auth basic module modules mod auth basic so LoadModule log config module modules mod log config so LoadModule env module modules mod env so LoadModule headers module modules mod headers so LoadModule unixd module modules mod unixd so LoadModule rewrite module modules mod rewrite so LoadModule proxy module modules mod proxy so LoadModule proxy http module modules mod proxy http so  IfModule unixd module  User daemon Group daemon   IfModule  ServerAdmin you example com  Directory        AllowOverride none     Require all denied   Directory  DocumentRoot   usr local apache2 htdocs  ErrorLog  proc self fd 2 LogLevel error  IfModule log config module      LogFormat   h  l  u  t    r     s  b     Referer i       User Agent i    combined     LogFormat   h  l  u  t    r     s  b  common      IfModule logio module      LogFormat   h  l  u  t    r     s  b     Referer i       User Agent i    I  O  combinedio       IfModule      CustomLog  proc self fd 1 common   IfModule   Proxy        AuthType Basic     AuthName GrafanaAuthProxy     AuthBasicProvider file     AuthUserFile  tmp htpasswd     Require valid user     RewriteEngine On     RewriteRule       E PROXY USER   LA U REMOTE USER  NS      RequestHeader set X WEBAUTH USER    PROXY USER e    Proxy  RequestHeader unset Authorization ProxyRequests Off ProxyPass   http   grafana 3000  ProxyPassReverse   http   grafana 3000         Create a htpasswd file  We create a new user   anthony   with the password   password         bash   htpasswd  bc htpasswd anthony password          Launch the httpd container using our custom httpd conf and our htpasswd file  The container will listen on port 80  and we create a link to the   grafana   container so that this container can resolve the hostname   grafana   to the Grafana container s IP address        bash   docker run  i  p 80 80   link grafana grafana  v   pwd  httpd conf  usr local apache2 conf httpd conf  v   pwd  htpasswd  tmp htpasswd httpd 2 4            Use grafana   With our Grafana and Apache containers running  you can now connect to http   localhost  and log in using the username password we created in the htpasswd file    If the user is deleted from Grafana  the user will be not be able to login and resync until after the  sync ttl  has expired        Team Sync  Enterprise only     Only available in Grafana Enterprise v6 3   With Team Sync  it s possible to set up synchronization between teams in your authentication provider and Grafana  You can send Grafana values as part of an HTTP header and have Grafana map them to your team structure  This allows you to put users into specific teams automatically   To support the feature  auth proxy allows optional headers to map additional user attributes  The specific attribute to support team sync is  Groups       bash   Optionally define more headers to sync other user attributes headers    Groups X WEBAUTH GROUPS       You use the  X WEBAUTH GROUPS  header to send the team information for each user  Specifically  the set of Grafana s group IDs that the user belongs to   First  we need to set up the mapping between your authentication provider and Grafana  Follow  these instructions    to add groups to a team within Grafana   Once that s done  You can verify your mappings by querying the API      bash   First  inspect your teams and obtain the corresponding ID of the team we want to inspect the groups for  curl  H  X WEBAUTH USER  admin   H  X WEBAUTH GROUPS  lokiteamOnExternalSystem  http   localhost 3000 api teams search      totalCount   2     teams                  id   1         orgId   1         name    Core          email    core grafana com          avatarUrl     avatar 327a5353552d2dc3966e2e646908f540          memberCount   1         permission   0                     id   2         orgId   1         name    Loki          email    loki grafana com          avatarUrl     avatar 102f937d5344d33fdb37b65d430f36ef          memberCount   0         permission   0               page   1     perPage   1000      Then  query the groups for that particular team  In our case  the Loki team which has an ID of  2   curl  H  X WEBAUTH USER  admin   H  X WEBAUTH GROUPS  lokiteamOnExternalSystem  http   localhost 3000 api teams 2 groups            orgId   1       teamId   2       groupId    lokiTeamOnExternalSystem             Finally  whenever Grafana receives a request with a header of  X WEBAUTH GROUPS  lokiTeamOnExternalSystem   the user under authentication will be placed into the specified team  Placement in multiple teams is supported by using comma separated values e g   lokiTeamOnExternalSystem CoreTeamOnExternalSystem       bash curl  H  X WEBAUTH USER  leonard   H  X WEBAUTH GROUPS  lokiteamOnExternalSystem  http   localhost 3000 dashboards home      meta          isHome   true       canSave   false                 With this  the user  leonard  will be automatically placed into the Loki team as part of Grafana authentication    An empty  X WEBAUTH GROUPS  or the absence of a groups header will remove the user from all teams     Learn more about Team Sync        Login token and session cookie  With  enable login token  set to  true  Grafana will  after successful auth proxy header validation  assign the user a login token and cookie  You only have to configure your auth proxy to provide headers for the  login route  Requests via other routes will be authenticated using the cookie   Use settings  login maximum inactive lifetime duration  and  login maximum lifetime duration  under   auth   to control session lifetime