Dailycode.info

Short solution for short problems

AngluarJS: Connect to a WebAPI using windows credentials and CORS

First sight this looked very easy. Just put the authentication on your web site to windows authentication. That's it! Or NOT? I kept getting an unauthorized error. So I discovered that I needed to add the withCredentials: true to the get request. 

Now the request looks like this:

var cf = headers: {
                'Content-Type': 'application/json; charset=UTF-8',
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
            };
$http.get(APIurl.qarAPI + 'qar/getUser', { withCredentials: true, cf })
    .success(function (data) {
        $rootScope.user = data;
    })
    .error(function (data, status) {
        console.error(JSON.stringify(data));
    });

Now the error message changed into this one:

Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials.

 This looked like a good exception that I would google in a minute. But it took some more time. The reason was because the problem was not on the web side, but on the .Net Web Api side. Eventually, I discovered that I needed to add this to the configuration of CORS on the web API:

config.EnableCors(new EnableCorsAttribute("http://localhost:101", "*", "GET, POST, OPTIONS, PUT, DELETE") { SupportsCredentials = true });

When I added this, user credentials are supported in the request and it works. My API call now needly gets the credentials of the windows user that made the request!

[HttpGet, Route("getUser")]
public HttpResponseMessage Get()
{
var identy = this.User.Identity;
 var resp = identy.Name;
 return Request.CreateResponse(HttpStatusCode.OK, resp);
}



AngularJS : Loving it

If made several apps in Angular, but this one is the first I finished completely and which I really like.

Its a card game helper for whist and another. In phase 2 I will try to implement translations, but I'm not sure if I will use an open source solution or develop one myself, because I have some ideas around this involving IndexDB.