Grafana 通过 Oauth 登陆

各单位版本

Grafana: v7.3.7 - Community < Docker >

修改 grafana 配置

1
vim /etc/grafana/grafana.ini

找到 [auth.generic_oauth]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[auth.generic_oauth]
;enabled = false
;name = OAuth
;allow_sign_up = true
;client_id = some_id
;client_secret = some_secret
;scopes = user:email,read:org
;email_attribute_name = email:primary
;email_attribute_path =
;login_attribute_path =
;id_token_attribute_name =
;auth_url = https://foo.bar/login/oauth/authorize
;token_url = https://foo.bar/login/oauth/access_token
;api_url = https://foo.bar/user
;allowed_domains =
;team_ids =
;allowed_organizations =
;role_attribute_path =
;tls_skip_verify_insecure = false

修改成如下:

1
2
3
4
5
6
7
8
9
10
[auth.generic_oauth]
enabled = true
name = OAuth
allow_sign_up = true
client_id = some_id # 自行修改
client_secret = some_secret # 自行修改
scopes = user:email,read:org
auth_url = http://项目访问地址/login/oauth/authorize # 自定
token_url = http://项目访问地址/login/oauth/token # 自定
api_url = http://项目访问地址/login/oauth/userinfo # 自定

增加接口

这里通过 Java 代码实现配置中配置的三个接口

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
@GetMapping("/login/oauth/authorize")
public String authorize(@RequestParam Map<String, String> param) {
System.out.println("/login/oauth/authorize");

param.forEach((k, v) -> {
log.info("{'key':'{}', 'value': '{}'}", k, v);
});

return "redirect:http://192.168.46.61:3000/login/generic_oauth?state=" + param.get("state") + "&code=123456";
}

@ResponseBody
@PostMapping("/login/oauth/token")
public Object token(@RequestParam Map<String, String> param) {
System.out.println("/login/oauth/token");
param.forEach((k, v) -> {
System.out.println("key=" + k + ",value=" + v);
});

Map<String, String> result = new HashMap<>(4);
result.put("access_token", "123456");
result.put("token_type", "fffff");
result.put("expiry_in", "");
result.put("refresh_token", "");

return result;
}

@ResponseBody
@GetMapping("/login/oauth/userinfo")
public Object userinfo(HttpServletRequest request) {
System.out.println("/login/oauth/userinfo");
System.out.println("header-authorization:" + request.getHeader("authorization"));

Map<String, String> result = new HashMap<>(2);
result.put("name", "gggg");
result.put("email", "ggggg@ggg");

return result;
}

测试

打开网站,访问 grafana,点击下图按钮即可

Grafana登陆页面

如果 /login/oauth/userinfo 接口中返回的邮箱不存在的话, grafana 会生成对应的账号。如果邮箱存在但是账号不同,会将新的覆盖掉旧的。

例如:

第一次返回 {“name”:”gggg”, “email”: “ggggg@ggg”},创建

图例1

第二次返回 {“name”:”ffff”, “email”: “ggggg@ggg”},更新

图例2