Angular+RESTful Client-side Communication w/ API for Auth/(re)Routing
This has been covered in a few different questions, and in a few different tutorials, but all of the previous resources I've encountered don't quite hit the nail on the head.
In a nut-shell, I need to
- Login via POST from
http://client.foo
tohttp://api.foo/login
- Have a "logged in" GUI/component state for the user that provides a
logout
route - Be able to "update" the UI when the user logs out / logs out. This has been the most frustrating
- Secure my routes to check for authenticated-state (should they need it) and redirect the user to the login page accordingly
My issues are
- Every time I navigate to a different page, I need to make the call to
api.foo/status
to determine whether or not user is logged in. (ATM I'm using Express for routes) This causes a hiccup as Angular determines things likeng-show="user.is_authenticated"
- When I successfully login/logout, I need to refresh the page (I don't want to have to do this) in order to populate things like
{{user.first_name}}
, or in the case of logging out, empty that value out.
// Sample response from `/status` if successful
{
customer: {...},
is_authenticated: true,
authentication_timeout: 1376959033,
...
}
What I've tried
- http://witoldsz.github.io/angular-http-auth/1
- http://www.frederiknakstad.com/authentication-in-single-page-applications-with-angular-js/2
- https://github.com/mgonto/restangular (For the life of me I could not figure out how to
POST
withpost data
and notquery params
. The docs turned up nothing on the matter.
Why I feel like I'm losing my mind
- It seems as though every tutorial relies on some database (lots of Mongo, Couch, PHP+MySQL, ad infinitum) solution, and none rely purely on communication with a RESTful API to persist logged-in states. Once logged in, additional POSTs/GETs are sent with
withCredentials:true
, so that's not the issue - I cannot find ANY examples/tutorials/repos that do Angular+REST+Auth, sans a backend language.
I'm not too proud
Admittedly, I'm new to Angular, and would not be surprised if I'm approaching this in a ridiculous way; I'd be thrilled if someone suggest an alternative—even if it's soup-to-nuts.
I'm using Express
mostly because I really love Jade
and Stylus
— I'm not married to the Express
' routing and will give it up if what I want to do is only possible with Angular's routing.
Thanks in advance for any help anyone can provide. And please don't ask me to Google it, because I have about 26 pages of purple links. ;-)
1This solution relies on Angular's $httpBackend mock, and it's unclear how to make it talk to a real server.
2This was the closest, but since I have an existing API I need to authenticate with, I could not use passport's 'localStrategy', and it seemed insane to write an OAUTH service...that only I intended to use.
I've created a github repo summing up this article basically: https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec
ng-login Github repo
Plunker
I'll try to explain as good as possible, hope I help some of you out there:
(1) app.js: Creation of authentication constants on app definition
(2) Auth Service: All following functions are implemented in auth.js service. The $http service is used to communicate with the server for the authentication procedures. Also contains functions on authorization, that is if the user is allowed to perform a certain action.
(3) Session: A singleton to keep user data. The implementation here depends on you.
(4) Parent controller: Consider this as the "main" function of your application, all controllers inherit from this controller, and it's the backbone of the authentication of this app.
(5) Access control: To deny access on certain routes 2 steps have to be implemented:
a) Add data of the roles allowed to access each route, on ui router's $stateProvider service as can be seen below (same can work for ngRoute).
b) On $rootScope.$on('$stateChangeStart') add the function to prevent state change if the user is not authorized.
(6) Auth interceptor: This is implemented, but can't be checked on the scope of this code. After each $http request, this interceptor checks the status code, if one of the below is returned, then it broadcasts an event to force the user to log-in again.
P.S. A bug with the form data autofill as stated on the 1st article can be easily avoided by adding the directive that is included in directives.js.
P.S.2 This code can be easily tweaked by the user, to allow different routes to be seen, or display content that was not meant to be displayed. The logic MUST be implemented server-side, this is just a way to show things properly on your ng-app.
This is taken from my blog post on url route authorisation and element security here but I will briefly summaries the main points :-)
Security in frontend web application is merely a starting measure to stop Joe Public, however any user with some web knowledge can circumvent it so you should always have security server-side as well.
The main concern around security stuff in angular is route security, luckily when defining a route in angular you are create an object, an object that can have other properties. The cornerstone to my approach is to add a security object to this route object which basically defines the roles the user must be in to be able to access a particular route.
The whole approach focuses around an authorisation service which basically does the check to see if the user has the required permissions. This service abstract the concerns away from the other parts of this solution to do with the user and their actual permission that would have been retrieved from the server during login. While the code is quite verbose it is fully explained in my blog post. However, it basically handle the permission check and two modes of authorisation. The first is that the user must have at least on of the defined permissions, the second is the user must have all of the defined permissions.
Now that a route has security you need a way of determining if a user can access the route when a route change has been started. To do this we be intercepting the route change request, examining the route object (with our new access object on it) and if the user cannot access the view we replace the route with another one.
The key here really is the '.replace()' as this replace the current route (the one they have not got rights to see) with the route we are redirecting them to. This stop any then navigating back to the unauthorised route.
Now we can intercept routes we can do quite a few cool things including redirecting after a login if a user landed on a route that they needed to be logged in for.
The second part of the solution is being able to hide/show UI element to the user depending on there rights. This is achieve via a simple directive.
You would then sure an element like so:
Read my full blog post for a much more detailed overview to the approach.
I've written an AngularJS module for UserApp that does pretty much everything you ask for. You could either:
https://github.com/userapp-io/userapp-angular
It supports protected/public routes, rerouting on login/logout, heartbeats for status checks, stores the session token in a cookie, events, etc.
If you want to give UserApp a try, take the course on Codecademy.
Here's some examples of how it works:
Login form with error handling:
Signup form with error handling:
How to specify which routes that should be public, and which route that is the login form:
The
.otherwise()
route should be set to where you want your users to be redirected after login. Example:$routeProvider.otherwise({redirectTo: '/home'});
Log out link:
<a href="#" ua-logout>Log Out</a>
(Ends the session and redirects to the login route)
Access user properties:
User info is accessed using the
user
service, e.g:user.current.email
Or in the template:
<span>{{ user.email }}</span>
Hide elements that should only be visible when logged in:
<div ng-show="user.authorized">Welcome {{ user.first_name }}!</div>
Show an element based on permissions:
<div ua-has-permission="admin">You are an admin</div>
And to authenticate to your back-end services, just use
user.token()
to get the session token and send it with the AJAX request. At the back-end, use the UserApp API (if you use UserApp) to check if the token is valid or not.If you need any help, just let me know :)
I haven't been using $resource because I'm just hand crafting my service calls for my application. That said I've handled login by having a service which depends on all the other services that get some sort of initialization data. When the login succeeds it triggers for initialization of all the services.
Within my controller scope I watch the loginServiceInformation and populate some properties of the model accordingly (to trigger the appropriate ng-show/hide). With regard to routing I'm using Angular's built in routing and I simply have an ng-hide based on the loggedIn boolean shown here, it shows text to request login or else the div with the ng-view attribute (so if not logged in immediately after login you're on the correct page, currently I load data for all views but I believe this could be more selective if necessary)
The HTML
The Base HTML that uses the parts above to complete the picture:
I have the login controller defined with an ng-controller higher up in the DOM so that I can change the body area of my page based on the loggedIn variable.
Note I haven't implemented form validation here yet. Also admittedly still quite fresh to Angular so any pointers to things in this post are welcome. Although this doesn't answer the question directly since it isn't a RESTful based implementation I believe the same can be adapted to $resources since it's built on top of $http calls.