Cors origins problem - connexion to web api

Hello,

I’m trying to connect grafana with my web API. but I got a CORS problem did anyone know how to solve it.

Nicolas

Hi @nicolasdossantos248 cors problems must be solved in your web API. It is your web API that should return the correct headers for it to work, more specifically the access-control-allow-origin. This has nothing to do with Grafana, this is the way brower’s security work

That being said, you should avoid querying your web api directly from the browser in your plugin and you should instead use proxy routes in your plugin so it is the grafana backend that fetches data from your API instead of the browser directly. You can read more about this here Add authentication for data source plugins | Grafana documentation

Hi Nicolas, I encountered the same issue throughout the entire day. I tried various solutions, including attempting to run a simple API call locally through PHP (which failed due to a CA certificate issue) and installing multiple new extensions. However, the solution turned out to be quite simple: I set up a reverse proxy in Nginx for my external API, like this:

server {
listen 443;
ssl on;
ssl_certificate /etc/ssl/certificate.crt;
ssl_certificate_key /etc/ssl/certificate.key;
server_name domainOfYourGrafana;
access_log /var/log/nginx/nginx.vhost.access.log;
error_log /var/log/nginx/nginx.vhost.error.log;
root /usr/share/nginx/html;
index index.html index.htm;

location /grafana/set-pause { // This is the path to my external API
    proxy_pass externaldomain.com;
    proxy_set_header Host externaldomain.com;
    proxy_set_header X-Real-IP $remote_addr; // No need to change this
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; // No need to change this
    proxy_set_header X-Forwarded-Proto $scheme; // No need to change this
    proxy_set_header Referer "https://domainOfYourGrafana.com";
}

}

So, in your request, instead of using externaldomain.com/grafana/set-pause, you can use domainOfYourGrafana.com/grafana/set-pause, and the proxy will handle the rest.

1 Like

Thank you for your answer, I forgot to say that I already fix the problem. I will give your solution a try when I will have time.

My API was in c# so I put this code in my Startup.cs:

services.AddCors(options =>
            {
                options.AddPolicy("GrafanaCors",
                    policy =>
                    {
                        policy.WithOrigins("http://localhost:3000")
                                .AllowAnyMethod()
                                .AllowAnyHeader()
                                .SetIsOriginAllowedToAllowWildcardSubdomains()
                                .AllowCredentials();
                    });
            });

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.