为 Grafana 配置统一身份认证,支持 LDAP 和 OAuth2 两种方式。

OAuth 认证(推荐)

grafana.ini 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
grafana:
grafana.ini:
# 全局认证配置
auth:
oauth_allow_insecure_email_lookup: true # 允许通过邮箱匹配用户

# OAuth 配置
auth.generic_oauth:
enabled: true
name: "OAuth"
client_id: "your-client-id"
client_secret: "your-client-secret"
scopes: "openid email profile offline_access"
# Authentik 端点
auth_url: "https://authentik.example.com/application/o/authorize/"
token_url: "https://authentik.example.com/application/o/token/"
api_url: "https://authentik.example.com/application/o/userinfo/"
# 安全配置
use_pkce: true
use_refresh_token: true
# 用户配置
allow_sign_up: false # 禁止自动注册
allow_assign_grafana_admin: true # 允许分配管理员
auto_login: true # 自动跳转登录
skip_org_role_sync: true

# 服务器配置
server:
root_url: "https://grafana.example.com/" # 必须正确配置

关键配置说明

配置项 说明 注意事项
root_url Grafana 访问地址 必须与实际域名一致,否则会重定向失败 issue#8673
oauth_allow_insecure_email_lookup 邮箱查找 使用邮箱匹配用户时需要设为 true
api_url Userinfo 端点 注意末尾的 /
use_pkce PKCE 支持 增强安全性

常见问题

重定向 URI 不匹配

报错:redirect_uri_mismatch

解决:确保 root_url 与 Grafana 实际访问域名一致。参考

LDAP 认证(备选)

ldap.toml 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
grafana:
ldap:
enabled: true
config: |
verbose_logging = true

[[servers]]
host = "ldap.example.com"
port = 389
use_ssl = false
start_tls = false
ssl_skip_verify = true

# 绑定用户
bind_dn = "cn=admin,dc=example,dc=com"
bind_password = "examplePassword"

# 搜索配置
search_filter = "(uid=%s)"
search_base_dns = ["ou=foo,dc=example,dc=com"]

# 组搜索
group_search_filter = "(objectClass=groupOfUniqueNames)"
group_search_base_dns = ["ou=Group,dc=example,dc=com"]
group_search_filter_user_attribute = "uid"

# 属性映射
[servers.attributes]
name = "cn"
surname = "sn"
username = "uid"
member_of = "memberOf"
email = "mail"

# 角色映射
[[servers.group_mappings]]
group_dn = "cn=g-admin,ou=Group,dc=example,dc=com"
org_role = "Editor"

grafana.ini:
auth.ldap:
enabled: true
config_file: "/etc/grafana/ldap.toml"
allow_sign_up: true

grafana.ini LDAP 配置

1
2
3
4
auth.ldap:
enabled: true
config_file: "/etc/grafana/ldap.toml"
allow_sign_up: true

配置对比

特性 OAuth LDAP
配置复杂度 简单 中等
统一登录 支持 不支持
离线访问 支持(Refresh Token) 需在线验证
适用场景 现代 SSO 架构 传统 LDAP 环境

参考文档

注意事项

  • root_url 配置错误是最常见的问题
  • OAuth 方式支持自动刷新 token,体验更好
  • LDAP 方式需要用户每次登录时在线验证
  • 生产环境建议禁用 allow_sign_up,手动管理用户权限