I have implemented Token based authentication in AngularJS, however my security api (which generates token) is windows based to centralize all AD interaction to one site.
The structure is as follows:
The flow is as follows:
This all works fine when the security and app were on the same domain, however as soon as the $http request needs to go across the domain, no Authorization header with windows credentials is sent causing a 401.
Security Api allows cross domain requests by allowing Origin's (* is only for testing not production):
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
Is it possible, and if so, how do you get the AngularJS client app to passthrough the windows credentials when making a cross domain $http request?
Try setting the withCredentials
property to true
when making the AJAX request to ensure that the client will send its credentials:
$http.get(url, { withCredentials: true, ...})
Basically what this flag will do is to set the withCredentials
property on the underlying XMLHttpRequest
native object.
Also you might need to include the Authorization
header on the server to the Access-Control-Allow-Headers
response.
My project is an Angular2-rc4 app calling a .NET Core 1.0.0 WebAPI cross domain. Adding to this answer in case it may help others.
I also posted this on this thread.
As mentioned by others, pass withCredentials true:
getUser() {
return this.http.get(this._apiUrl + "/account/GetUser", { withCredentials: true })
.toPromise()
.then(response => response.json().data)
.catch(this.handleError);
}
In your WebAPI project you can set CORS policies in Startup.cs (instead of web.config):
public void ConfigureServices(IServiceCollection services)
{
var corsBuilder = new CorsPolicyBuilder();
corsBuilder.AllowAnyHeader();
corsBuilder.AllowAnyMethod();
corsBuilder.AllowAnyOrigin();
corsBuilder.AllowCredentials();
services.AddCors(options =>
{
options.AddPolicy("AllowAll", corsBuilder.Build());
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors("AllowAll");
}
Of course, set your policies based on your app's needs, this just allows all for testing. Example here and official .NET Core docs here provide more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With