So, you are building pure client side application that works against REST API. The client and server are completely decoupled and typically deployed separately of each other.
API’s have one or another way of authenticating it’s users. It could be some simple flows, like basic authorization or more complex ones as OAuth/OAuth2. But at the very end you have token that placed either as cookie value or HTTP request header parameter. API is then responsible to check the token for validity and if it’s not valid respond with 401.
Configure the Routes
First we need to have /login router where user is redirected in case of unauthorized access.
The authentication controller is simple module. It’s responsible for sending user credentials to server and handle the response. If server authenticates user, it would return the value of access token in .token attribute. Otherwise, user have to be notified that something went wrong.
Ones server responds with success, controller will place the token to cookie.
The view is just a form with binded ng-submit event to call auth.login() function of controller.
<divclass="login-panel"><h1>Welcome to Analytics.</h1><p>We are using GitHub for authorization. Please obtain your personal token and use it to sign in.</p><formclass="pure-form"ng-submit="login()"><inputtype="password"class="pure-input-1-3"placeholder="Personal Token..."name="token"ng-model="token"required/><buttontype="submit"class="pure-button pure-button-primary">Sign in</button></form></div>
In case of any API call returns 401 we have to redirect user to login page. Angular’s HTTP interceptor is great for that job. As you can see from app.js above, it’s been pushed to pipe here:
Posted by Alexander Beletsky. If you liked that material, please consider to follow my twitter account for further updates. If you have comments or questions, do not hesitate to contact my email or raise issue on github.