How we implemented ALD Pro user authorization via Keycloack using Grafana as an example

3. Setting up Keycloak for connection with Grafana

In the Grafana console, go to menu → Clients → Create client.

Next, create a client as in the pictures below.

Then go to the settings of the created client on the Credentials tab, save the Client Secret. It will be needed later when configuring from the client application.

We copy the endpoint links where Grafana will contact to authenticate users. To do this, go to menu → Realm settings → OpenID Endpoint Configuration.

We are interested in those that end in auth, token, userinfo.

4. Launch Keycloak

The main setting is the Keycloak service startup parameter:

/opt/keycloak/keycloak-22.0.1/bin/kc.sh start --hostname aldbln01.int:1024
--http-relative-path /key --hostname-admin-
url=https://aldbln01.int:1024/key/

If after running the command kc.sh start Keycloak will ask you to build with the new parameters, then you need to run the command: */kc.sh build.

The –hostname parameter means the url where Keycloak will work. In the –hostname parameter we set the name of our proxy server (NGINX) and the port it will listen on (aldbln01.int:1024).

The –http-relative-path parameter must match the name of the location in NGINX (in our case /key) from which the service will operate.

The –hostname-admin-url parameter is required to access the admin console. We manually set its url (https://aldbln01.int:1024/key/).

5. Setting up NGINX

Install NGINX from the repository using the command apt install nginx -y (in our booth OS Astra SE 1.7.4). In the etc/nginx/sites-enabled directory, move or rename the standard configuration file, and then create a new aldbln.conf file in it. Below is a description of the configuration in the aldbln.conf file:

server {
 
        listen 80;
        listen 1024 ssl default_server;
        ssl_certificate /etc/nginx/Cert.pem;
        ssl_certificate_key /etc/nginx/Key.pem;
 
        server_name aldbln01.ald.int;
        location /key {
                proxy_pass https://aldkeycl01.ald.int;
        }
        location /grafana/ {
                proxy_pass http://aldweb01.ald.int:3000;
 
        }
                }

To work using the https protocol, it is enough to issue a key and a self-signed certificate based on it.

To work with Grafana, http 80 and https 1024 ports are listened to (port 1024 was taken for testing, by default you can use 443). The user's request is redirected (proxy_pass) to the domain name Grafana web01:3000 (if http(s):// nlb/grafana is specified in the request address).

Example: https://aldbln01.ald.int/grafana.

Keycloak also listens to http 80 and https 1024 ports (port 1024 is taken for testing, by default you can use 443) and redirects to the location (/key) if such a path is present in the http request.

Example: https://aldbln01.ald.int/key.

6. Setting up Grafana

All Grafana settings are specified in the configuration file /etc/grafana/grafana.ini.

Add a section with OAuth authentication anywhere (but not in the middle of another section). In the example, it is located immediately after the section [server]):

#exampleHeader1 = exampleValue1
#exampleHeader2 = exampleValue2// конец раздела server, копировать не нужно
########ADDED FOR KEYCLOAK############
 
[auth.generic_oauth]
enabled = true
scopes = profile email openid
email_attribute_path = email
login_attribute_path = username
name_attribute_path = full_name
oauth_allow_insecure_email_lookup = true
name =Keycloak-OAuth
tls_skip_verify_insecure = true
allow_sign_up = true
client_id = grafana2
client_secret = OEHvGwD***********8vHb
auth_url = https://aldbln01.ald.int/realms/adrealm/protocol/openid-connect/auth
token_url = https://aldkeycl01.ald.int/realms/adrealm/protocol/openid-connect/token
api_url = https://aldkeycl01.ald.int/realms/adrealm/protocol/openid-connect/userinfo
 
__________________________________________
Параметр scopes проверяет области из KeyCloak. Доступные области можно 
посмотреть в административной консоли KeyCloak в разделе "Client scopes"
*_attribute_path — пути к атрибутам, которые будет проверять Grafana. При 
кастомных названиях можно поменять их в соответствии с названиями атрибутов в KeyCloak.
Параметр client_id должен соответствовать ID клиента в KeyCloak.
Параметр client_secret — необходимо вставить тот секрет, который сохраняли ранее
*_url — скопировать точные ссылки на endpoint, которые ранее видели в KeyCloak.
...
domain = aldweb01.ald.int
...
http_port = 3000
...
root_url = http://aldbln01.ald.int/grafana/
...
serve_from_sub_path = true
...
auth_url = https://aldbln01.ald.int:1024/key/realms/adrealm/protocol/openid-connect/auth
token_url = https://aldkeycl01.ald.int/key/realms/adrealm/protocol/openid-connect/token
api_url = https://aldkeycl01.ald.int/key/realms/adrealm/protocol/openid-connect/userinfo
...
signout_redirect_url = https://aldbln01.ald.int:1024/key/realms/adrealm/protocol/openid-connect/logout?post_logout_redirect_uri=http://aldbln01.ald.int/grafana&client_id=grafana2
__________________________________________
Параметр domain — прописать имя хоста, где работает сервис grafana.
Параметр http_port должен соответствовать тому, который указан на прокси сервере Nginx.
Параметр root_url — из него Grafana генерирует redirect url при запросе в KeyCloack,
а как мы помним пользователь находится в другой подсети, так что здесь 
указывается «прокси» имя.
Параметр serve_from_sub_path задается, чтобы Grafana могла работать из 
локации /grafana. (как в нашем примере)
Параметр auth_url — та ссылка, по которой Grafana перенаправит пользователя 
для аутентификации и ввода логина/пароля. Так что она должна проксироваться.
Параметр token_url ,api_url — бэковые endpoint, по которым Grafana будет обращаться 
напрямую в Keycloack. Скопировать их из OpenID endpoint из консоли 
администратора Keycloack.
Параметр signout_redirect_url (если что, это все одна строка) — ссылка, по которой
Grafana перенаправит пользователя, когда он нажмет кнопку signout. Чтобы успешно 
попасть на форму логаута в KeyCloack, затем вернуться в Grafana (а не застрять 
в межинтернетном пространстве) и проксировать оба адреса.

It is also important to make changes to the Server section, since the default settings will redirect to localhost. It is necessary not only to write down the desired value, but also to remove the “;” at the beginning of the line.

[server]
# Protocol (http, https, h2, socket)
protocol = http
 
# This is the minimum TLS version allowed. By default, this value is empty. 
Accepted values are: TLS1.2, TLS1.3. If nothing is set TLS1.2 would be taken
;min_tls_version = ""
 
# The ip address to bind to, empty will bind to all interfaces
;http_addr =
 
# The http port to use
http_port = number of your port
 
# The public facing domain name used to access grafana from a browser
domain = yourhostname.example.com
 
# Redirect to correct domain if host header does not match domain
# Prevents DNS rebinding attacks
;enforce_domain = false
 
# The full public facing url you use in browser, used for redirects and emails
# If you use reverse proxy and sub path specify full url (with sub path)
;root_url = %(protocol)s://%(domain)s:%(http_port)s/

Next you need to save all changes and restart Grafana. A new button with OAuth authentication should appear on the login page:

7. Checking the work

The proxy address /grafana should open the Grafana console from the aldweb01 server. All you have to do is click the “Sign in with Keycloak” button.

The authentication page that is specified in the Grafana settings (auth_url) will open. Next, enter the ALD Pro user credentials.

Thanks to the root-url parameter in the Grafana settings, Keycloak will successfully return the user back to Grafana already authorized. Now all you have to do is click the “Log out of account” button.

Grafana will transfer via the link specified in the signout_redirect_url parameter.

The exit was successful! Hooray!

Instead of a conclusion

In this article, we only looked at the core of the solution. For combat implementations, it is necessary to configure a cluster of balancers, implement roaming of VIP addresses, and select a balancing method between backends. Keycloak itself must be implemented in high availability mode, but these are details.

As a result, we received a solution that helped us solve the main problem. It is now possible to publish corporate services using a single sign-on service. This allows our customers to switch to import-substituted catalog services, in particular ALD Pro, and not worry about the operation of the services that are integrated with it.

This solution and many others can be viewed in detail on our stand import substitution.

Alexander Kozlov

Computer systems design engineer

Grigory Ektov

Implementation engineer of the department of biometric technologies and authentication systems

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *