I am currently facing an issue with my angularjs HTML client connected to a WebApi project. The APIs work fine when tested using POSTMAN or other REST clients. However, when I try to use browsers with my angularjs client, the browsers always initiate preflight requests with OPTIONS. At this point, my WebAPI consistently responds with a 400 Bad Request error, specifically during the "/api/token" phase.
I have meticulously debugged every aspect of my WebAPI project and made adjustments based on various responses from the SO community on enabling CORS. Some of the methods I have attempted include modifying the web.config to add headers enabling CORS for every request, integrating CORS into the WebApi startup process, and enabling CORS for "/token" overridden functions.
My Angularjs TypeScript call to "/api/token" looks like this:
logIn = (userName: string, userPassword: string): ng.IPromise<void> => {
var postData = {
"grant_type": "password",
"client_id": this.appConfiguration.ClientId,
"client_secret": this.appConfiguration.ClientSecret,
"username": userName,
"password": userPassword
};
return this.$http.post<models.LoggedUserModel>('http://local.web.api/api/token', $.param(postData), {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then((result) => {
this.localStorageService.set('Auth', result);
this.goHome(true);
}).catch((error) => {
console.warn(error);
});
}
Here is the primary function called in my WebApi:
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
// Handle CORS requests
if (!string.IsNullOrEmpty(context.OwinContext.Request.Headers.Get("Origin")))
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new string[] { "*" });
}
try
{
// Retrieve clientId and clientSecret from the request body
string clientId;
string clientSecret;
if (context.TryGetFormCredentials(out clientId, out clientSecret))
{
// Execute our specific application security code....
}
else
{
// This is part of enabling CORS
if (context.Request.Method.ToUpper() == "OPTIONS")
{
context.Validated(); // Return OK to preflight requests with empty body
}
}
}
finally
{
// Log activities...
}
}
Despite leaving out OWIN Cors configurations, adding headers, and calling 'context.Validated()', the issue persists. The behavior I am encountering is detailed below:
Firefox Network Tab:
--------------------
Request URL: http://local.web.api/api/token
Request method: OPTIONS
Remote address: 127.0.0.1:80
Status code: 400 Bad Request
Version: HTTP/1.1
...
I would greatly appreciate any suggestions on how to proceed with this issue as it is a new challenge for me, although I have experience with other WebApi projects and angularjs integration.