1gn1ter 1gn1ter - 2 months ago 28
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:

[Authorize]
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
})
.subscribe(
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())
.catch(this.handleError);

//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
  1. Install-Package Microsoft.Owin.Cors
  2. Add to App_Start > Startup.Auth.cs > ConfigureAuth(IAppBuilder app)

       app.UseCors(CorsOptions.AllowAll);
    

Only one line. That's all.

Comments