I am building a large application with Web API and AngularJs. I built the secure web api with authentication and claim-based authorizations. One requirement is that different users can view different modules on the same template.
I am new to AngularJs. I did the authentication in client side with the tokens. Also, in web api, I created a service to get all the permission given a user id. The response is a list of resource(contoller)/action(method) pairs. How do I implement the correct layout based on authorization rules on client side? Does that solely rely on web api permissions response and show/hide (ng-hide/ng-show) content based on the permissions?
Is this a good approach? What other modules/directives do I need to look into? Such as the loader for not loading the nested route until user request the parent route.
To add complexity, this site also need to work in bi-lingual. I think ng-translate. I mentioned this because it may open up another discussion on whether this may favor MVC instead of AngularJs. But the preference is Angular if the above two problem can be resolved.
All the authentication & authorisation & validation should be done server-side. You can adjust the user interface based on the roles/claims the server tells the browser the current user has.
One way to do this is to create something like a roles/userprofile controller, which will respond with a list of roles the current user has. On the client side you’ll probably want something you can inject everywhere, so you’re able to determine user interface behaviour.
myApp.factory(‘myUser’, function(Roles, $q) {
// Create a promise to inform other folks when we’re done.
var defer = $q.defer();
// For this example I’m using ngResource
Role.query({
/*
No params — let the server figure out who you ‘really’ are.
Depending on WebApi configuration this might just be
as simple as this.User (in context of the controller).
*/
}, function(roles) {
var user = {
roles: roles,
isInRole: function(role) {
return user.roles.indexOf(role) !== -1;
}
};
defer.resolve(user);
});
return defer;
});
Because the factory above is returning a promise we can enforce that myUser is resolved before a certain route/controller instance is created. One little trick I use is to gather all my route definitions in one object, loop through them with an angular.forEach and add a resolve.myUser property to each of them. You can use this to pre-load/initialize other stuff too.
Now inject the myUser anywhere you like:
myApp.controller(‘MyController’, function($scope, myUser) {
// Expose it on the current scope
$scope.myUser = myUser;
});
… and in your markup …
<div class=“my-content-thingy”>
<p>Lorem del ipsum …</p>
<button class=“btn” ng-if=“myUser.isInRole(‘content-editor’)”></button>
</div>
Note: You’ll probably want to use ng-if and not ng-show; the latter keeps the element in the DOM.
Just keep in mind that you don’t authenticate anything on the client side; that all done server side. A simple way is to place Authorize attributes on the appropriate controller actions.
Hope this helps.
A proper approach is to build AngularJS routing configuration as per Authorization on the server. This should be build just after the user is authorized and before the AngularJS app is initialized. That way the authorized user sees a "complete" app based on his roles etc. Using ng-show/ng-hide is not a good way to do it. Also each view should be doing only one thing. So load separate views based on the task that needs to be completed.
Regarding multi language support, this is independent of Authorization. Some time ago, I wrote a custom AngularJS filter that used the jQuery i18next plugin. It was a pretty simple implementation.
However you can now use https://github.com/i18next/ng-i18next
(Sorry for misunderstanding the problem).
I think that using ng-hide/show is not much of a problem. At the end of the day, the user does not have access to the data. I think it should rely on the api permissions + show/hide of presentation. Depends on the complexity you want... You can use MVC with angularjs since it's a large application.
Related
I have developed a profile page which contains several modules such as, let's say : personal info and friends.
Each modules is a ng-controller which makes database calls but I would like to be able to pass the id of the user of whom the profile is being displayed so that database calls are dynamics and retrieve data related to this user.
How I am supposed to do that?
Thanks in advance,
Manuel
* Clarification *
I am using express.js which handles authentication and session management (with Passport).
Once the user is logged in he reaches the "/profile" page.
I didn't particularly want to handle routing on several sides so I decided to handle all routing on Node side. So I have created routes for get and post calls.
Now, when the user arrives on "/profile" I would like the different modules (personnal info, friends, etc.) to update based on the person connected.
I managed to do non-dynamic call :
app.controller('UserInfo', [
'$scope', '$http',
function($scope, $http) {
$http.get("/api/users/info/1")
.then(function(response) {
$scope.user = response.data.local;
});
}
]);
But this doesn't depend on the context. So I would like now to create get calls the same way but being able to pass the id (or any other proper way) of the user to retreive his data.
Would you have any recommendation as to how to proceed? Any link to tutorials on how to handle this in multi-page MEAN application? Most of documents I found on the internet are related to single-page applications and don't answer my need.
Thanks!
If your UI handle who am I, you will get some security breach.
Your server need to know who is connected. (with a cookie or something like that).
Here is an exemple : https://blog.nodejitsu.com/sessions-and-cookies-in-node/
We have a multi-tenant Angular JS single page application. The routing for the application uses a customer identifier as part of the URL - #/home/<KEY> or #/search/<KEY>/<search term> for instance. In theory the first page served could be of any type. Each page calls an API using the customer key and other values picked up from the URL to get data for the page. So far so good.
We have some parameters - a logo, copyright statement, default language (for internationalization) - that can be loaded using a separate API call that also uses the customer KEY. These parameters need to be available as strings in partials, to drive the internationalization and perhaps in controllers.
The question is where to call the API to get these parameters and how to set them / make them available for the rest of the app. I have looked at a bunch of questions in this general area but can't find a concrete suggestion. Should we use a config in app.js? Call another script from index.html?
Appreciate people's advice.
The right place would be to make an API call immediately after authentication to get the various Customer specific configuration data like the Customer settings for logo, language and then put them in the session storage of the browser.
I have done an implementation using Microsoft ADAL js as per the documentation given here. https://github.com/AzureAD/azure-activedirectory-library-for-js/blob/dev/README.md.
You can do this Api call in the login success event handler or similar ones in angular.
Example:
$scope.$on("adal:loginSuccess", function () {
$scope.testMessage = "loginSuccess";
});
HTH
In my AngularJS app, I need to retrieve multiple collections of static data from remote REST endpoints. Those data collections will be used throughout the entire application life cycle as static lookup lists. I would like for all those lists to be populated upon the initial application startup, and to be retained and made available to multiple controllers. I would prefer not to load any additional data dynamically, as one of the assumptions for this particular app, is that, once loaded, any further network connections may not be available for a while.
It is OK to take an initial hit, as the users will be preoccupied by reading a static content of the first page anyway.
I was thinking of making this mass loading a part of the initial application run block, and stick all this static data into various collections attached to the $rootScope (which would make that available everywhere else)
What is the best way to handle this requirement?
Interestingly enough, I just wrote a blog post about extending the script directive to handle this very scenario.
The concept is simple. You embed JSON data in your page when it loads from the server like so:
<script type="text/context-info">
{
"name":"foo-view",
"id":34,
"tags":[
"angular",
"javascript",
"directives"
]
}
</script>
Then you extend the script directive so it parses the data out for you and makes it available to other parts of your application via a service.
if(attr.type === 'text/context-info'){
var contextInfo = JSON.parse(element[0].text);
//Custom service that can be injected into
// the decorator
contextInfoService.addContextInfo(contextInfo);
}
You can see a live demo of it here: http://embed.plnkr.co/mSFgaO/preview
The way I approach this is to use a service (or a collection of services I nest), and set caching to true in the $http get functions. This way the service can be passed into any controller you desire, having cached results available to you without the need for additional http requests.
I can try to put this into an example if this is unclear to you, let me know.
edit: you can either wait for the first call to this service to do this caching, or do this on app load, either way is possible.
Is there a blog, project, gists or seed out there using angularjs and requirejs that provides authentication not based on routes? I'm working on building a site that will show the user the same rendered view, but different data fed from the server based upon their authentication. I have session handling already written into it, but I need angular to check the server for the session on the initial render for changing login buttons to logout and getting only the data the user wants to see that they've selected.
I attempted to use the angular run method to initially grab the session from the server, but when using requirejs, my app module doesn't exist at the time of calling the run method.
From my understanding, please correct me if I'm wrong, I should be creating an injector or using the $rootScope to carry the user information to routed controller and show the user what they is related to them. If so, then I need to have a service that is initially fired during the project instantiation to retrieve the user's session data. I'd prefer to not use the servers template rendering to put the users session data into javascript if possible.
I have an application which has some specific (non-trivial) initialization requirements, and it's not really clear what the best practice solution to this is. Sorry for the wall of text. The question itself is not that complex, but I need to make sure my reasoning is clear.
First, the application itself:
It has user authentication, though it is only forced at two points in time:
The first time the application is loaded (the very first time). I'll just call this requirement (1) through the rest of the question.
On a need-to basis when interacting with server-side. This part I have already solved with something similar to http://ngmodules.org/modules/http-auth-interceptor, though a custom solution (which is required because the application needs to use some services that I don't want to be Angular dependent). I'll call this requirement (2) through the rest of the question.
There are two controllers relevant to this question:
A navigation bar controller (fixed, not bound to the view).
The controller applied to the view used (ng-view).
It is started manually using angular.bootstrap.
This question is about the user authentication handling. Requirement (2), where a user has to authenticate on a need-to basis, is already solved. It is currently handled like the following:
Some server-side request is performed by one of my Angular service modules. The request can potentially result in a 401 response if the applied authentication token has expired (or doesn't exist all-together).
The application service module which made the request discovers the 401 response and applies a $rootScope.$broadcast('app:auth').
The authentication broadcast is picked up by some code using $scope.$on('app:auth'), shows a modal authentication dialog, and then makes sure the original service request promise is resolved / rejected (rejected if the user presses cancel in dialog).
The only differences between requirement (1) and (2) is that (1) should be a forced authentication dialog (the user cannot simply reject it with 'cancel' or 'esc'-button) and that (1) should happen as early in application initialization as possible.
Now, my issue is with requirement (1), really, and Angular best practices. There are a couple of ways to do this that I can see:
Perform this one-time authentication outside of Angular completely. The downside here is obviously that I have to write essentially duplicate logic for both the modal dialog box and the initialization. Some of this can be shared, but not all.
Perform this one-time authentication in some special (fixed) controller of the application (like the navigation bar controller).
Perform this one-time authentication in angular.module.run.
The aim here is obviously to "force" an authentication on the user before he (or the application) can trigger something else in the application.
I would love to use number (3), since I would then be able to re-use all code already in use by requirement (1). However, you then instead run into the question of where to place the event-listening code. No controllers / parts of the application are yet started at this point (only the injections are complete).
If I place the logic for authentication events in an application controller, that controller won't even have started at that point, and thus won't have been able to register with the event. If I place the $rootScope.$broadcast inside a $timeout with 0 delay, my navigation bar controller have started, but not my view-bound controller. If I place the $rootScope.$broadcast inside a $timeout with 100 ms delay, both my controllers have started (on MY computer).
The issue obviously being that the amount of delay I need to use is dependent on the computer and exactly what scope the event handler code is placed in. It's also probably dependent on exactly in which order Angular initialize the controllers found through-out the DOM.
An alternative version of (3) might also be to do the $rootScope.$broadcast in angular.module.run, and have the event-listener attached to the $rootScope itself. I'm leaning towards this being the most straith-forward way to do it.
See the following plunker (which tries to higlight the timing issue only): http://plnkr.co/edit/S9q6IwnT4AhwTG7UauZk
All of this boils down to the following best-practice question, really:
Where should application-wide code and non-trivial application initialization code really be placed? Should I consider the $rootScope as the actual "application"?
Thanks!
The short answer :
Application wide code should be in a service.
Application initialization code should be in the run block.
Longer answer :
Application wide code like your Authentication should be defined in a service. This service should expose API's which the rest of your application can interact with in order to achieve that task. Ofcourse the job of the service is to hide the implementation details. The service itself should take care of where it fetches the authentication information from ( initially ) - perhaps from cookies, perhaps from your local storage or session storage.. Or perhaps it even does a http call. But all this gets encapsulated into that Authentication Service.
Because now you have written a separate service and you can inject stuff into your run block you are good to go. You dont really need the $rootScope. The $rootScope is another injected service. But because it participates in the dirty checking mechanism and seemingly this service need not.. you dont need to over burden $rootScope with this additional task. Its not its job and perhaps it can be delegated to some other service whose only task is authentication. Because your service is also a singleton it is amazing at maintaining states as well. You could perhaps set a flag , something like isAuthenticated which can be checked later if need be.
Oh, between your modal should also be a service.. See the $dialog service in Angular UI if you havent already. Which means that authentication can directly work with the $dialog service.
You should put application-wide non-trivial initialization code in providers. Providers offer the most flexibility with regards to initialization, because they can be used to configure the service before the instance of the service is actually created by the $injector.
app.provider('service', function() {
// add method to configure your service
this.configureService = function() { ... };
this.$get = function (/*injectibles*/) {
// return the service instance
return {...};
};
});
The config block is your opportunity to initialize your providers. Inject your provider into your config function (notice the required 'Provider' suffix) and perform any initialization code that you need to setup your provider. Remember, that the provider is not the service - it is the thing that the $injector will use to create your service.
app.config(function(serviceProvider) {
serviceProvider.configureService();
serviceProvider.setTimeout(1000);
serviceProvider.setVersion('1.0);
serviceProvider.setExternalWebService('api/test');
... more configuration ...
};
There are several reasons why providers and config blocks are suitable for initialization:
config blocks are called only once and very early in the application life cycle
providers are configurable - meaning you can initialize the provider before actually creating the service.
The main purpose of the config block is initialization. It supports injection of providers as an opportunity to perform the initialization.
Providers are singletons (like factories and services) - meaning that one service instance is created by the $injector and then shared between all controllers, directives, etc - basically any where that the service is injected.
Now for requirements (1) and (2) - I think you're on the right track. I suggest creating an authLogin directive that shows or hides a modal login dialog based on an "IsAuthenticated" property that is being watched on the scope. This would take care of the requirement to show the login modal dialog when the application starts up. Once the user authenticates successfully, set the IsAuthenticated property to true (which would then hide the dialog).
The second requirement is handled through an HTTP interceptor. When a request is made and the user is not authenticated, the service would broadcast the event starting from the $rootScope downwards towards the child scopes. You can have the same authLogin directive listen for the event and handle it by setting the IsAuthenticated property to false. Since IsAuthenticated is a watched property, it would trigger the modal login dialog so the user can log in again.
There are many ways you could implement requirements (1) and (2). I offered a slight variation on your approach, but in general it is the same approach.