6

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.

1
  • 1
    where you able to solve the problem, I am facing exactly the same one Commented Sep 15, 2019 at 14:06

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

options.AllowCredentials() is needed for http post to work and it fixed the CORS issue
1

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);

1 Comment

Thanks for your answer. RequestOptions has been deprecated, so I feel I should avoid it. In the interests of debugging I tried it anyway and got the same 401 behaviour.
0

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.

Comments

0

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
})); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.