CORS Error when trying to access the REST API from myopenHAB Server

I want to develop a Programm, which communicates with the myopenHAB Server. I created an API Key, but I get a CORS Error. Why? Should I send the credentials (login information) also?

Simple App to connect:

export class OpenhabDataServiceService {
  private apiKey = 'oh.app.KEY';

  constructor(private http: HttpClient) {}

  sendRequest(itemName: string, command: string): Observable<any> {
    const url = `https://home.myopenhab.org/rest/items/${itemName}`;
    
    // Setzen Sie den Content-Type und den API-Schlüssel in den Header
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'text/plain',
        'Authorization': `Bearer ${this.apiKey}`
      })
    };

    // Führen Sie den POST-Request mit dem Befehl aus
    return this.http.post(url, command, httpOptions);
  }
}

  1. the token you have generated is not for myopenhab and is local to your oh instance, so when you hit “home.myopenhab.org” , it has no idea who you are or how to lookup your connection.

  2. Maybe if you explain what this code is, language, environment, etc… like is this running in a browser or in node? Were is it being served from? … someone might be able to help better. CORS errors are browser generated, all servers do is return CORS headers and let the browser decide what to do.

The cloud service does support BASIC auth, so your cloud credentials can be used for remote rest calls.

  1. The Token is working - but I get a CORS Error in my Webapp (Angular). If I make a PHP Script, which forward the GET and POST Requests, it works fine, but this is not what I want. I want to communicate instant with the myopenhab.org REST API.
  2. The question is: How can I set the right Headers, that my webapplication is allowed to instant communicate with the openHAB Rest API?

Is it even possible to set cors info to myopenhab cloud service?

CORS is browser side validation of server answers. When you hook page you are building to external domain then your browser will issue CORS request to see if browser is permitted to fetch data from it. This is OPTIONS request which returns several headers (allowed http methods etc) and status code. Non 20x status code is interpreted by browser as show stopper which prevents further interactions.
When you proxy your call through PHP script or your own domain then browser does not issue CORS call cause everything happens within same domain.
For server CORS is transient as it does not impact processing. It is however essential for JS to allow cross site requests which might be considered as a security threat in many cases.

1 Like

Yes all right, but is there a way to accept the CORS Problem at myopenHAB.org? This is what i want to reach at this thread.

HI Mark, you gave a little more info, but still have not responded to all my questions, so its really hard to help you . Specifically, where is it being served from? If you serve the app from your OH instance, which can be done in the conf/html, then that the app will be served from the same domain as your OH instance or myopenhab (depending if inside/outside home network). Same orgin / domain CORS issues should be satisfied.

This is not an openHAB issue per se, i would suggest reading

The question is: Can a Webapp in Angular / vue.js or React communicate with the openHAB Cloud REST API? If I want to connect it, there is a error because of CORS. On Server Site ( in this case the openHAB Cloud) should give access to the IP Adress of the frontend. This is the way of how it is normally done, but can openHAB Cloud also do this? Can my local instance of openHAB do this?

Please read up on CORS, i think it would answer all you questions. If you serve the app from within the conf/html directory of you openHAB instance, then you can access that through myopenHAB and CORS will not be an issue. If you are trying to host this on a different domain, then CORS is an issue. This is standard practice for webapps. myopenHAB is not designed as a generic API service, and circumventing the default CORS policy to allow any webapp from any domain is inviting a security risk to our user base i’m not comfortable doing (we have a LOT of users on myopenhab) .

Can my local instance of openHAB do this?

Again, openHAB does not do any thing special, running the app so openHAB serves it from the same domain ( as seen in your browser bar) as the underlying REST api will satisfy CORS, running it from another ip/domain will probably not.

is it possible to run the webapp in conf/html and then communicate directly with the items via the REST API?

the point of cors is that a client must be authenticated with the server. So - then it is obvious to me that this is possible in openHAB, that I can authorise the client IP.

I’m not sure i know what you mean when you say “run”. Most angular apps are single page applications (SPA) run in the browser, so just a bunch of javascript/html/css/image files that get served by a web server. I’m assuming there’s no server side rendering (I don’t know anyone using that in Angular, although it is supported).

Anything you put in your conf/html directory will be served by your openHAB under the “static” path in openhab. So for example if your angular app is in a folder called my-app, and you put it in conf/html/my-app then you will be able to load it in a browser at “http://openhab:8080/static/my-app/index.html” (assuming index.html is in this folder, and openhab:8080 is where your openhab is running). You can also access this in myopenhab like “https://home.myopenhab.org/static/my-app/index.html” although you will need to deal with authentication to myopenhab which can be tricky (this is not a standard use case).

Nope, authentication with a server has nothing to do with CORS, and Its hard to have this conversation if you do not do some homework here. By serving the app from the same domain that the app is also requesting REST from, your browser will be happy and not complain about CORS. The server is dumb here, its actually not doing anything to block requests, all it can do is make a recommendation to the browser about what policies it supports, and its up to the browser to comply. We don’t do anything to bypass this.

Thank you for your concrete answear. Maybe I will check the html solution what you wrote.

What excactly is my goal?
I want to develop my own App with Angular and connect it to my openHAB instance.

Why?
openHAB is great with the Addons it has. Also the UI is nice, but I want to make it myself. At the other hand i dont want to programm each api by myself.

What is the solutions I found?
There are two solutions hwo you can bypass cors errors, if the server can´t be configured.
The first one: Making a Proxy Server at backend like Flask, Django, NodeJS, JavaSpring
The second one: Bypass the Angular App by itself: Angular Proxy: How to Bypass CORS Errors Using proxy.conf.json | by Navneet Singh | Medium

This is webpack dev server configuration which will work only with … dev server instance. You’ll need another proxy mechanism when app is bundled and deployed in the wild.

so you say this only works for dev state?

Yes. To my actual knowledge, anything which relates to webpack runs on browser side with exempt of dev server which is a side process serving you during development time.

sorry but what is this? If I get an API Token, then this is the best way to develop my own app. But I think then I have also CORS Error if this is an Web App

API token is one of the ways you can use to authenticate your call once it reaches server. This means that you still have to solve proxy/cors stuff to benefit from it.

Ok so I should create a Proxy with Python and Flask for example. Host it on Heroku and then connect openHAB to the Backend Server and the Frontend Server connects to the Backend?