or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

admin-and-rbac.mdalerting.mdauthentication.mdclient-management.mddashboards.mddata-models.mddatasources.mdindex.mdlibrary-elements.mdplugin-management.mdsnapshot-management.mdusers-and-orgs.md

authentication.mddocs/

0

# Authentication

1

2

Authentication classes and methods for secure access to the Grafana API. The grafana-client supports multiple authentication mechanisms including API tokens, custom headers, and basic authentication to accommodate different Grafana deployment scenarios and security requirements.

3

4

## Capabilities

5

6

### Token Authentication

7

8

Bearer token authentication using Grafana API tokens for secure API access. This is the recommended authentication method for production use.

9

10

```python { .api }

11

class TokenAuth:

12

"""

13

Bearer token authentication for Grafana API.

14

15

Args:

16

token (str): Grafana API token

17

"""

18

def __init__(self, token: str): ...

19

```

20

21

**Usage Example:**

22

23

```python

24

from grafana_client import GrafanaApi, TokenAuth

25

26

# Create token auth with your API token

27

auth = TokenAuth(token="glsa_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx_yyyyyyyy")

28

29

# Use with GrafanaApi

30

api = GrafanaApi(auth=auth, host="your-grafana-host")

31

api.connect()

32

```

33

34

### Custom Header Authentication

35

36

Custom header-based authentication for specialized authentication schemes or proxy configurations.

37

38

```python { .api }

39

class HeaderAuth:

40

"""

41

Custom header authentication for Grafana API.

42

43

Args:

44

name (str): Header name (e.g., 'X-API-Key', 'Authorization')

45

value (str): Header value

46

"""

47

def __init__(self, name: str, value: str): ...

48

```

49

50

**Usage Example:**

51

52

```python

53

from grafana_client import GrafanaApi, HeaderAuth

54

55

# Create custom header auth

56

auth = HeaderAuth(name="X-API-Key", value="your-api-key")

57

58

# Use with reverse proxy authentication

59

proxy_auth = HeaderAuth(name="X-WEBAUTH-USER", value="admin")

60

61

api = GrafanaApi(auth=proxy_auth, host="your-grafana-host")

62

api.connect()

63

```

64

65

### Basic Authentication

66

67

Basic HTTP authentication using username and password credentials. Pass as a tuple to the auth parameter.

68

69

```python { .api }

70

# Basic auth is passed as tuple (username, password)

71

auth_tuple = (username: str, password: str)

72

```

73

74

**Usage Example:**

75

76

```python

77

from grafana_client import GrafanaApi

78

79

# Use basic authentication with username/password tuple

80

auth = ("admin", "your-password")

81

82

api = GrafanaApi(auth=auth, host="your-grafana-host")

83

api.connect()

84

```

85

86

### Factory Method Authentication

87

88

Authentication can be configured automatically when using factory methods for client instantiation.

89

90

**From URL:**

91

92

```python

93

from grafana_client import GrafanaApi

94

95

# URL with embedded credentials

96

api = GrafanaApi.from_url(

97

url="https://admin:password@your-grafana-host:3000",

98

credential="optional-token-or-credential",

99

timeout=10.0

100

)

101

```

102

103

**From Environment Variables:**

104

105

```python

106

import os

107

from grafana_client import GrafanaApi

108

109

# Set environment variables

110

os.environ['GRAFANA_URL'] = 'https://your-grafana-host:3000'

111

os.environ['GRAFANA_TOKEN'] = 'your-api-token'

112

os.environ['GRAFANA_TIMEOUT'] = '10.0'

113

114

# Create client from environment

115

api = GrafanaApi.from_env(timeout=10.0)

116

```

117

118

**Supported Environment Variables:**

119

120

- `GRAFANA_URL` - Complete Grafana URL (e.g., "https://admin:password@grafana.example.com:3000")

121

- `GRAFANA_TOKEN` - API token for TokenAuth (alternative to credentials in URL)

122

- `GRAFANA_TIMEOUT` - Request timeout in seconds (float)

123

124

### Authentication with Async API

125

126

All authentication methods work identically with the async API:

127

128

```python

129

import asyncio

130

from grafana_client import AsyncGrafanaApi, TokenAuth

131

132

async def main():

133

auth = TokenAuth(token="your-api-token")

134

api = AsyncGrafanaApi(auth=auth, host="your-grafana-host")

135

136

await api.connect()

137

version = await api.version

138

print(f"Connected to Grafana {version}")

139

140

asyncio.run(main())

141

```

142

143

### Custom Authentication

144

145

For advanced scenarios, you can implement custom authentication by extending the `niquests.auth.AuthBase` class:

146

147

```python

148

import niquests.auth

149

from grafana_client import GrafanaApi

150

151

class CustomAuth(niquests.auth.AuthBase):

152

"""Custom authentication implementation"""

153

154

def __init__(self, custom_token: str):

155

self.custom_token = custom_token

156

157

def __call__(self, r):

158

# Add custom authentication to request

159

r.headers['X-Custom-Auth'] = f"Bearer {self.custom_token}"

160

return r

161

162

# Use custom authentication

163

auth = CustomAuth("your-custom-token")

164

api = GrafanaApi(auth=auth, host="your-grafana-host")

165

```

166

167

## Error Handling

168

169

Authentication errors are represented by specific exception types:

170

171

```python { .api }

172

class GrafanaUnauthorizedError(GrafanaClientError):

173

"""Raised for 401 Unauthorized errors"""

174

pass

175

176

class GrafanaClientError(GrafanaException):

177

"""Base class for 4xx HTTP errors"""

178

pass

179

```

180

181

**Handling Authentication Errors:**

182

183

```python

184

from grafana_client import GrafanaApi, TokenAuth, GrafanaUnauthorizedError

185

186

try:

187

auth = TokenAuth(token="invalid-token")

188

api = GrafanaApi(auth=auth, host="your-grafana-host")

189

api.connect()

190

except GrafanaUnauthorizedError as e:

191

print(f"Authentication failed: {e.message}")

192

print(f"Status code: {e.status_code}")

193

except Exception as e:

194

print(f"Connection error: {e}")

195

```

196

197

## Security Best Practices

198

199

1. **Use API Tokens**: Prefer TokenAuth over basic authentication for better security

200

2. **Store Credentials Securely**: Use environment variables or secure credential stores

201

3. **Rotate Tokens Regularly**: Implement token rotation policies

202

4. **Use HTTPS**: Always use HTTPS in production (set `protocol="https"`)

203

5. **Verify SSL**: Keep SSL verification enabled (default `verify=True`)

204

6. **Limit Token Scope**: Create tokens with minimal required permissions

205

7. **Monitor Token Usage**: Track API token usage and revoke unused tokens

206

207

**Secure Configuration Example:**

208

209

```python

210

import os

211

from grafana_client import GrafanaApi, TokenAuth

212

213

# Secure configuration

214

auth = TokenAuth(token=os.environ['GRAFANA_TOKEN'])

215

api = GrafanaApi(

216

auth=auth,

217

host=os.environ['GRAFANA_HOST'],

218

protocol="https", # Use HTTPS

219

verify=True, # Verify SSL certificates

220

timeout=10.0, # Reasonable timeout

221

organization_id=int(os.environ.get('GRAFANA_ORG_ID', '1'))

222

)

223

224

try:

225

api.connect()

226

print("Successfully authenticated with Grafana")

227

except Exception as e:

228

print(f"Authentication failed: {e}")

229

```