Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Angular2 + Windows Authentication
protected void Application_BeginRequest()
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
protected void Application_BeginRequest()
{
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
Response.Flush();
}
}
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable()
export class MyService {
private serviceUrl: string = 'http://localhost:3620';
constructor(private http: Http) { }
get() {
// need to have { withCredentials: true }
return this.http.get(`${this.serviceUrl}/api/values`, { withCredentials: true })
.toPromise()
.then(r => r.json())
.catch(r => console.log(r));
}
}
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="accept,Content-Type, Authorization" />
<add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true"/>
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
var corsAttr = new EnableCorsAttribute("*", "*", "*");
corsAttr.SupportsCredentials = true;
// Enable CORS Globally
config.EnableCors(corsAttr);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment