Integrate grafana in your own java application

created at 09-20-2021 views: 27

Grafana is a very good visualization report tool with well-designed visualization tools. Today, let’s talk about how to integrate grafana into your application.

The principle is:

  • Grafana allows iframe access, open auth.proxy, and proxy grafana after java back-end authentication
  • The front-end accesses the back-end proxy grafana through an iframe

grafana configuration

To integrate, you can choose the iframe integration method, and you need to configure it to be embedding

[security]
allow_embedding = true

In addition, you also need to consider the issue of authentication. You can turn on auth.proxy and pass in authentication information through the http header:

[security]
allow_embedding = true

[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 = Auth
# 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
sync_ttl = 60
# 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 =
# Check out docs on this for more details on the below setting
enable_login_token = false
default_theme = light

Since the default is the black theme, the effect of integrating into the system is not beautiful, you can set the default theme to light.

In order to facilitate the external authentication proxy, you can set sub_path and root_url

[server]
root_url = http://0.0.0.0:3000/grafana
serve_from_sub_path=true

java backend configuration

Introduce httpproxy

        <dependency>
            <groupId>org.mitre.dsmiley.httpproxy</groupId>
            <artifactId>smiley-http-proxy-servlet</artifactId>
            <version>1.11</version>
        </dependency>

add config:

proxy:
  grafana:
    servlet_url: /grafana/*
    target_url: http://grafana_url/grafana

Add proxy servlet:

/**
 * Acting as a management panel for Grafana
 */
public class GrafanaProxyServlet extends ProxyServlet {

    @Override
    protected HttpResponse doExecute(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
                                     HttpRequest proxyRequest) throws IOException {
        String currentUser = SecurityUtils.getCurrentUserLogin().orElse(null);
        if(currentUser == null){
            return null;
        }
        // set user
        proxyRequest.setHeader("Auth", currentUser);
        return super.doExecute(servletRequest, servletResponse, proxyRequest);
    }
}

Register servlet:

@Configuration
public class ProxyServletConfiguration {
    /**
     * Read the routing settings in the configuration file
     */
    @Value("${proxy.grafana.servlet_url}")
    private String servlet_url;

    /**
     * Read the proxy target address in the configuration
     */
    @Value("${proxy.grafana.target_url}")
    private String target_url;

    @Bean
    public ServletRegistrationBean proxyServletRegistration() {
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new GrafanaProxyServlet(), servlet_url);
        //Set URL and parameters
        Map<String, String> params = ImmutableMap.of("targetUri", target_url, "log", "true");
        registrationBean.setInitParameters(params);
        return registrationBean;
    }
}

Frontend configuration

Add a new vue page, and fill in the grafana panel that the back-end proxy has been used for the iframe address.

<template>
  <div class="grafana">
    <iframe
      :src="url"
      width="100%"
      height="1000px"
      frameborder="0"></iframe>
  </div>
</template>

<script>
export default {
  data() {
    return {
      url: '/grafana/d/FN0S0R47z/qian-duan-ri-zhi-mai-dian?orgId=1&kiosk&from=now-6h&to=now'
    }
  }
}
</script>

When debugging, you can configure webpack proxy:

      '/grafana': {
        target: 'http://172.31.161.36:13000',
        changeOrigin: true,
        headers: {
          'Auth': 'viewer'
        },
        pathRewrite: {
        }
      },

headers Add Auth authentication headers.

Integration preview:

Integration preview

created at:09-20-2021
edited at: 09-20-2021: