Which is a common way to implement oauth2 auth on the angular-based single page application? Is it possible to implement it without page reload? If not - what is a best way to transfer auth data back to angular code from the page?
1 Answer
The authorization server must provide an api to authenticate user and return access token without redirecting. I will take facebook as authorization server and resource server in this example for easier understanding. The flow is like this:
Your user clicks on a button on the page.
Since this is SPA built with angularjs, the browser sends an ajax to your server to get data.
On server side, you find out that this action requires data from resource server (facebook), instead of redirecting the browser to resource server as we usually do, the server sends a response with a custom status (or any information indicating that this action needs an access token) to the browser.
On browser, when you receive response from server in your ajax success callback function. You can check the response and find out that this action needs an access token
The browser first tries to get this access token from resource server (if the user is already logged in). When working with facebook using FB javascript SDK, we usually use FB.getLoginStatus function.
a. If we can get the access token in the success callback (the user is already logged in), just send this access token to server to get data (using ajax).
b. If the user is not logged in yet, use javascript to prompt the user to login by rendering a login button and the user has to click on it. When working with facebook using FB javascript SDK, we usually use FB.login function when user clicks on the login button. After successful login, we will receive the access token in the success callback and just send it to server to get the response (using ajax).
There is no page reload because all actions are done with ajax (without browser's redirects)
8 Comments
popup window, not our main page. Quote from the doc: Calling FB.login results in the JS SDK attempting to open a popup window. As such, this method should only be called after a user click event, otherwise the popup window will be blocked by most browsers. When the user finishes login we will get the response (access token,..) in the success callback.