Socrates
Socrates

Reputation: 9594

Losing session at every REST call

I have an Angular app on http://localhost:4200/myfrontend that gets data from a Java REST api on http://localhost:8080/mybackend. Within the Angular app though, every time I reach out to the REST api a new session is created.

I created a test where I put both frontend and backend on http://localhost:8080 and the session was not lost.

The settings I set for the Java REST backend are:

response.getHeaders().add("Access-Control-Allow-Origin", "*");
response.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
response.getHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");

The settings I set for the Angular 6.0.5 frontend are:

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  })
};

What must I do to keep alive the session when the frontend and backend URL are both different? Is this a missing CORS setting?

Upvotes: 1

Views: 1317

Answers (1)

Atul
Atul

Reputation: 541

Currently, both URLs have their own individual sessions. What you essentially need is a "backend to backend” communication. You can achieve this by using a dev-server proxy.

A dev-server proxy is a piece of software which is in between your JavaScript/Angular app doing the Ajax request and your backend API.

So, Assuming Instead of doing this -

this.http.get('http://you-server-hostame:8080/mybackend/...')
.map(res => res.json());

Use

this.http.get('/mybackend/')
.map(res => res.json());

Create a proxy.conf.json file at the root of your angular CLI project.

{
 "/mybackend/*": {
"target": "http://8080:<your service port>",
"secure": false,
"logLevel": "debug",
"changeOrigin": true
 }
}

All requests made to /mybackend/... from within our application will be forwarded to http://8080:/....

Also now for starting the server you need to use

ng serve --proxy-config proxy.config.json

Note :the changeOrigin property. You will definitely have to set this to true when you’re using some virtual proxies (such as configured with Apache2) on your backend.

What it does is to simply take the browser request at the same domain+port where you frontend application runs and then forwards that request to your backend API server.

Disclaimer: Not recommended for Production

Upvotes: 2

Related Questions