MGDavies
MGDavies

Reputation: 1054

Angular WithCredentials not working for POST, PUT

I'm working on an Angular site with:

• .Net Framework server on localhost/test

• client on localhost:4200

I've got cookie authentication working, and my GET requests are working fine.

   this.httpClient.get<Test>('dummyUrl', { withCredentials: true });

In my web.config for the server I have the following.

    <add name="Access-Control-Allow-Credentials" value="true"/>
    <add name="Access-Control-Allow-Origin" value="http://localhost:4200" />
    <add name="Access-Control-Allow-Methods" value="*" />

Given this setup I'd expect the same to work for PUT and POST requests.

    this.httpClient.put('dummyUrl', this.payload, { withCredentials: true });

I get a 401 Unauthorized from this.


My Investigation

The request method I see made is OPTIONS, which tells me that this is failing on the pre-flight, and that this issue relates to CORS rather than Angular. I've been unable to work out what I'm missing.

I'd be grateful for any guidance.

Upvotes: 6

Views: 14292

Answers (4)

Ntsako
Ntsako

Reputation: 1

For anyone using a node.js server this was the fix for me, using the cors package which you can install with npm i cors

const cors = require('cors');

app.use(cors({ 
  origin: 'http://localhost:4200', 
  credentials: true
})); 

Upvotes: 0

A SHAHZAD
A SHAHZAD

Reputation: 176

if you are using in asp net core api with angular on front end, then in web api, start up setting (under configure method),

set following setting

        app.UseCors(options =>
        {
            options.SetIsOriginAllowed(origin => true);
            //options.AllowAnyOrigin();
            options.AllowAnyHeader();
            options.AllowAnyMethod();
            options.AllowCredentials();   <-- This one is important
        });

and it should work.

Upvotes: 4

Pfuufy
Pfuufy

Reputation: 1

I was having similar problems too, even with {withCredentials: true} on my POST requests.

In my Spring Boot server's code, where it deals with CORS, I had the Access-Control-Allow-Origin header set to *. I changed * to http://localhost:4200, where my Angular app was being served from.

Things worked fine after that. Hope this helps someone.

Upvotes: 0

Arun Raj R
Arun Raj R

Reputation: 2317

Try the following code.

import { RequestOptions, Headers } from '@angular/http';

let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers, withCredentials: true });

this.httpClient.put('dummyUrl', this.payload, options);

Upvotes: 1

Related Questions