I'm facing a dilemma because I understand that Javascript isn't designed for synchronous work, especially in the case of AngularJS. However, I find myself in a situation where I require it.
The main page on the "www" domain (built with AngularJS) makes frequent calls to an API. Some of the resources on the API demand authentication, resulting in a 401 error. AngularJS detects this and prompts a login box when encountered.
The www-login feature supports various login methods and sends the credentials to the API. The API responds with a token, which the Angular app stores in a cookie and sets in
$http.defaults.headers.common['Authorization']
to authenticate future requests to the API. This method also retrieves the username associated with the API token.
This system functions effectively and meets my design requirements. However, when a browser navigates to a URL requiring authentication, the 401 error triggers the login box to appear. It seems that Angular is unable to populate the Authorization field in the header before the 401 response reaches the browser.
Possible Solutions:
- Utilize async=false request using jQuery?
- Dismiss the login box after obtaining the necessary data, even if it results in flickering.
- Store additional metadata about the login (such as username) in cookies to avoid server retrieval during app loading.
- ??
Is there a more optimal solution? In this particular instance, I wish to incorporate async=false in my Angular resource for this specific request.