How to handle security in angularjs.
Please explain with proper example, with demo source code.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Mukil VendhanRank #2,971 · 486 reputationPosted Sep 24, 2017, 8:41 AM EDT
Define roles for the application:
These are the roles which you would like to keep for authorization in the application. It is necessary to keep them global as these would be used by both at App module scope and service scope.
This is the route where you would want the user to go, if he is not authorized to see any page.
We would be using this variable later, in the App module routes.
This is the heart of the whole authorization. Angular service (or factory) is singleton and persisted across different routes of application, for a given user session. We can leverage this feature of service to do authorization on different routes. In order for you to create the service, you would need a service (like Web API) at server side, which can give you a set of roles for a given user. Once roles are procured from server side, then Angular service can persist this knowledge to be re-used for all routes, during the session of user. I have tried to explain the service code below with inline comments.
Let's use all our hard work done so far to secure the routes. So far, we created a service which is capable of checking if a user falls under a particular role or not. This knowledge can be used in the angular routes now. In the angular module, where we define routes, we can put these checks to see if the user has access to any of the roles specified for a route. I have put combinations of roles in these routes, to ensure better understanding.