1gn1ter 1gn1ter - 1 year ago 138
TypeScript Question

Enabling WebAPI CORS for Angular 2 authentification

I've seen a few answers on stackoverflow and I'm lost.

I have webapi 2 + standalone angular 2
webapi project is from template. the only thing i've changed is that i added CORS
and following line to IdentityConfig.cs > ApplicationUserManager Create()

context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "http://localhost:3000" });

here I've all standard from template:

public class ValuesController : ApiController
// GET api/values
public IEnumerable<string> Get()
return new string[] { "value1", "value2" };

On the client side I have function to get access token, that works properly:

authenticate(loginInfo: Login): boolean {

let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.http.post(this.baseUrl + 'Token', 'grant_type=password&username=alice2@example.com&password=Password2!',
headers: headers
data => this.saveAuthToken(<AccessToken>(data.json())),
err => this.handleError(err),
() => console.log('authentication Complete')

return true;

And get function, that works ok without authentication (commented code) :

get(url: string) {

var jwt = sessionStorage.getItem(this.idTokenName);
var authHeader = new Headers();
if (jwt) {
authHeader.append('Authorization', 'Bearer ' + jwt);

return this.http.get(this.apiUrl + url, {
headers: authHeader
.map(res => res.json())

//return this.http.get(this.apiUrl + url)
// .map(res => res.json())
// .catch(this.handleError);

But when i try to add Authorization header server returns:

XMLHttpRequest cannot load http://localhost:3868/api/values. Response for preflight has invalid HTTP status code 405

How to allow user to authenticate through Angular properly?

Answer Source
  1. Install-Package Microsoft.Owin.Cors
  2. Add to App_Start > Startup.Auth.cs > ConfigureAuth(IAppBuilder app)


Only one line. That's all.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download