Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Consuming restful api calls with windows authentication

I have a .net web api hosted on IIS 7 on a remote server which uses windows authentication. I want to access the web api using Angular 2 using TypeScript with node. Earlier i was getting an error 'Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource'

I added this on the hosted Application's web.config

<httpProtocol>
 <customHeaders>
   <add name="Access-Control-Allow-Origin" value="*" />
 </customHeaders>

But now i get Unauthorised 401 error. I have read about adding the following code to allow cross domain access - but I don't have any idea where do i add this in the angular 2 app and how to compile.

app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,     Content-Type, Accept");
next();
});
app.get('/', function(req, res, next) {
// Handle the get for this route
});
app.post('/', function(req, res, next) {
// Handle the post for this route
});

Here is the sample code for service that I am trying to make the get call with

@Injectable() 
export class TodoService {
todos$: Observable<Todo[]>; 
private _baseUrl: string;
private _todosObserver: Observer<Todo[]>;
private _dataStore: {
    todos: Todo[]
};

constructor(private _http: Http) {
    //let headers: Headers = new Headers();

    this._baseUrl = 'http:/SampleServer/Server/api/LoadTodo';
  this.todos$ = new Observable(observer => this._todosObserver = observer).share();
  this._dataStore = { todos: [] };
}

loadTodos() {
    let headers: Headers = new Headers();
    //headers.append('Access-Control-Allow-Origin');
    headers.append('Authorization', 'Basic ' +
        btoa('username:password'));
    //let opts: RequestOptions = new RequestOptions();

    //opts.headers = headers;
    this._http.get(`${this._baseUrl}`,headers).map(response => response.json()).subscribe(data => {
        this._dataStore.todos = data;
        this._todosObserver.next(this._dataStore.todos);
    }, error => console.log('Could not load todos.'));
}

Any help to resolve this issue would be great.

like image 719
A Singh Avatar asked Jan 21 '26 06:01

A Singh


2 Answers

You need to check if the Authorization header is correctly sent within your request. If you forgot to import the Headers class, the header won't be sent:

import {Http, Headers, ...} from 'angular2/http';

Another option would be that, since you are in the case of a preflighted request (GET method with the Authorization header), an OPTIONS request is sent. In fact, this request is transparently sent by the browser and the credentials are present in it. So you don't have to check security here on the server side. Otherwise you will have a 401 error since the server won't be able to authenticate the request...

See these articles for more details:

  • http://restlet.com/blog/2015/12/15/understanding-and-using-cors/
  • http://restlet.com/blog/2016/09/27/how-to-fix-cors-problems/
like image 159
Thierry Templier Avatar answered Jan 23 '26 18:01

Thierry Templier


I have stumbled upon the same problem when using Angular 2 within an ASP.NET Core solution. For me, I had the explicitly specify withCredentials: true:

  getSomeModels() {
      return this.http.get(this.apiBasePath + 'models', { withCredentials: true })
          .map(res => res.json());
  }

CORS must be enabled on the server side (Web API) and no other changes were required on the client side.

NOTE: Server side code to enable CORS (Startup.cs)

public void ConfigureServices(IServiceCollection services)
{
    // injected services
    services.AddAuthorization();
    services.AddMvc();

    //db context

    var corsBuilder = new CorsPolicyBuilder();
    corsBuilder.AllowAnyHeader();
    corsBuilder.AllowAnyMethod();
    corsBuilder.AllowAnyOrigin(); // For anyone access.
    corsBuilder.AllowCredentials();

    services.AddCors(options =>
    {
        options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
      // middleware configuration

      app.UseCors("SiteCorsPolicy");
}
like image 26
Alexei - check Codidact Avatar answered Jan 23 '26 18:01

Alexei - check Codidact



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!