What is the Best way to manage state in AngularJS - angularjs

I am a ASP.Net developer and trying to learn AngularJS. There are several ways to manage state in asp.net such as Session, ViewState, Cookies etc.
Can someone explain me or direct me to a good example which is showing state management best practices in angularJs.
For example once user log in to the application I want to store the current user object in client side.

There are many ways to maintain states. You can maintain a state, either using "$scope", or "$rootScope" in AngularJS.
For example :-
angular.module('SampleApp')
.controller('ExampleCtrl', ['$scope', '$rootScope', ExampleCtrl])
function ExampleCtrl($scope, $rootScope) {
// for set data
$scope.data="Hello";
$rootScope.Globaldata="Hello World";
}
In above example, "$scope" is used for page level or local variable and "$rootScope" is used for maintaining the state globally.
You can access the value of "$rootScope" anywhere in your application, whereas you don't use the value of "$scope".
Another way to store or to maintain data, is using LocalStorage:-
You can store your value using "angular-local-storage" and "ngCookies".
Follow Below Link :-
https://docs.angularjs.org/api/ngCookies/service/$cookies

You can use angular-local-storage, ngCookies to save states and provide persistence. Additionally you can use IndexedDB storage in newer browsers to provide persistence, with the condition that its not available in all the browsers.
A better strategy is to use combination of IndexedDB, localStorage, ngCookies with a fallback to in-memory storage. In order to do this you need to have a consistent api/ service which provides this functionality and handles the fallback gracefully within the service itself so that the consumer of the service doesn't need to bother about the fallback mechanism

Checkout this library https://www.npmjs.com/package/angularjs-store
This can help you manage your application state much simpler as it will force you to have a one way data flow on your application.

Ng-Cookies
You could add the Angular service ng-cookies this lets you store and retrieve cookies when you inject it into you module. Here is a link to the docs.
Add new service
To add a new service to you angular app you will first need to download the js files and add them too you index.html like (from CDN)
<script type="text/javascript" src=""//ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-cookies.js""></script>
Load into app
In any module you want to use ng-cookies inject like this
angular.module('app', ['ngCookies']);
Conclusion
Your app now has access to the read and write cookie methods that come with ng-cookies But remember that the CookieStore service is depreciated so only use ng-cookie
from Angular Docs
Note: The $cookieStore service is deprecated. Please use the $cookies service instead.
Beyond this the Docs are pretty good. Best of luck.

There are a lot of ways in which this could be done. I use sample codes based on https://github.com/alarv/ng-login in my applications. I'm using tokens to authenticate the requests.
The sample code demonstrates
saving user information in a service called "Session".
2.statechangeEvents to handle authentication with roles.
interceptors to handle authentication/ authorization errors in http
requests.
If you are securing the html resources also, you might need to redirect the page to login page from the server side.

That highly depends on what kind of authentication mechanism you are using on back end.I use token based and session less systems for my projects so I use browsers local storage for storage of authentication tokens but if you are using sessions you will need to use cookies.
If you use local storage make sure you use JSON.stringify() first when saving and on retrieval of that Object make sure you use JSON.parse()
Disadvantage of localstorage : only html5 supported
So if your website needs to give support to older browsers you will need to have a fallback on cookies.

Related

Handling auth in Chrome Extension MV3

I am building my first ever Chrome browser extension and I am struggling to find the right solution for handling authentication. There is a requirement that the extension stay logged in as long as possible, to reduce the need for the user to log in often. This means we would need to use Refresh Tokens. I would very much like to handle all authentication on the background script but this is no longer persistent in MV3 nor does it have access to the DOM.
This being the case, I see these options:
use Auth0 React SDK on the content scripts - this means all my authentication logic will run in a somewhat less secure environment but the token will be handled by the library and I will be able to access it in all my content and popup scripts (if I need persistence across page refreshes, I would still need to use localStorage, I believe). But this means that the background script will not have access to the token and it will need one of the other scripts to retrieve it and send it through a message
implement the Authorization Code Flow with PKCE following the steps in this tutorial on the background script - this will mean that all my auth logic is running in a more secure environment but I don't have a way of storing the token, other than using chrome.storage. It's also a bit tricky to silently retrieve the token (or check if user is still logged in) from the background script (it can be done using an injected iframe and the web_message response type or with chrome.identitybut there are still issues with the redirect_uri which needs to be listed in the Allowed Origin config of the Auth0 app - so you can only easily do this on the pages of the extension).
I know that the recommended solution for an SPA is using the SDK but I would like to know if this is also the right solution for a browser extension. Based on this article on Token Storage, localStorage is dangerous especially due to third-party scripts. Seeing that the MV3 manifest has now removed the ability to execute remote code, is localStorage an acceptable way to store tokens?
I have implemented both options using the docs provided but I am unsure as to what is the best solution, given the changes introduced by MV3.
Thank you

Serve REST-API data in web-page without exposing API-endpoint

I am beginner in MEAN stack.
When invoking unauthenticated REST API (no user log-in required), API end-points are exposed in the JS files. Looked through forums that, there is no way to prevent abusers using the API end-point directly or even creating their own web/app using those end-points. So my question is, are there any way to avoid exposing the end-points in the JS files?
On a similar note, are there any ways, not to use REST calls on front-end and still be able to serve those dynamic content/API output data in a MEAN stack? I use EJS.
There's no truly secure way to do this. You can render the page on the server instead, so the client only sees HTML (and some limited JS).
First, if you don't enable CORS, your AJAX calls are protected by the browser, i.e. only pages served from domain A can make AJAX calls to domain A.
Public API providers like Google Maps protect themselves by making you use an API key that they link to a Google account.
That key is still visible in the JS, but - if abused - can be easily disabled.
There's also pseudo-security through obfuscation, i.e. make it harder for an attacker to extract a common secret you are using the encrypt the API interaction.
Tools like http://javascript2img.com/ are far from perfect, but makes attackers spend a lot of time trying to figure out what your code does.
Often that is enough.
There are also various ways to download JS code on demand which can then check if the DOM it runs in is yours.

Handling/Pushing File Updates to User Browsers?

When I make a change to my Backbone web application code on my server, how can I make user's browsers update so they see those changes.
Being a SPA the page rarely if ever refreshes. So even if place hashes/timestamps on my script tags it still wont be adequate enough, ie, this isn't ideal IMO:
...
<script src="js/main.js?t=SOME_HASH"></script>
Does Backbone have a way to handle this?
Backbone being a JS framework that merely gives structure to your applications, it doesn't handle stuff like this. This is something that involves configuration of server and you need to tackle it yourself.
Since you said you have an SPA that rarely refreshes - Your app is probably contacting the server via lots of AJAX requests. You can add an interceptor to these requests on the server that checks if stuff changed on server and sends a shouldReload: true with the response.
You should also have an AJAX interceptor client side that checks for this in response and reloads the page/lets users know about updates on server and give option to reload/restart.
Another option is to implement websockets/polling so that server can push notification about changes to clients. socket.io is a plugin that uses web sockets and falls back to polling.
P.S: You also need to bust the cache as you mentioned in question

Angular 1.x : Specific Scenario When To Use Controller / Service

Let's say, In a web app, a particular JSON is frequently used across multiple pages, for e.g:
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
So getting a firstName() or lastName() for all employees should be considered as a part of the controller or the Service?
I could only think of using services as it is frequently used across app and controller be getting this data and it will be thinner too.
Is this right approach ?
You have following options:
Make a REST/HTTP call every time you need this data in a certain controller. Therefore, create a EmployeesService which calls the HTTP
endpoint to get the data.
Call the data once, and store it in a service. Afterwards, inject the service everywhere you need the data.
Fetch the data from the HTTP endpoint when your app starts, and store it in the local storage of the browser or inside the $rootScope,
so you can access it from everywhere.
In the end, it depends on:
How big is your app/how much data you have to share?
How often gets this data updated?
Which Views do need access to this data?
So yes, with a service, you are on a safe side. Afterwards, inject it into the controller and use it from there. How and how often the data gets into the service: Your decision.

Recommended authentication UX in AngularJS SPA with own and external (Google, FB...) profiles

I'm developing an Asp.net MVC + Web API + AngularJS SPA. I would like to have several types of registration/authentication:
own profile provider
external providers ie Google, FB etc.
Possible scenarios
As I'm having an SPA it would be best if I could keep my user on my page while external (or internal for that matter) would be taking place. I'd display a modal layer with particular content loaded (maybe even inside an iframe). Can this be done? Online examples?
Have login/registration capability implemented as usual Asp.net MVC full page reload controller/views and then redirect back to my SPA when that is successful. Also redirect to external provider if users wanted to authenticate/register using external provider.
Any other possibility?
Questions
How did you do this similar scenario in your SPA or how would you recommend to do it?
Should I be using particular authentication patterns regarding this - for instance provide my internal authentication/registration similar to external one so SAP would always behave in the same way
I will also have to authenticate my Web API calls subsequently after user athenticated themselves in the SPA. Any guidance on that?
I can only comment on my own experience, maybe it is helpful. We use the same stack as you, Asp.net MVC + Web API + AngularJS. We use server-side MVC for authentication (Microsoft.AspNet.Identity), since we are not exposing a public API at this stage and the only consumer of the API will be our SPA this works perfectly with the least amount of effort.
This also enables us to set a UserContext Angular service on the server once logged in that can be shared through your entire Angular app, the Google Doubleclick Manager guys goes into some of the benefits of this approach during there ng-conf presentation. Since Web Api supports Asp.Net Identity, authentication and authorization works seamlessly between MVC and Web Api.
To sum up the major pros and cons:
Pros:
Very easy and quick to implement.
Works across MVC and Web Api.
Clientside code does not need to be concerned with authentication code.
Set UserContext Angular service on server side once during login, easily shared throughout SPA using Angular DI. See presentation as mentioned above.
Integrates with external providers as easily as you would with any normal MVC app.
Cons:
Since the browser does not send the hash # part of the URL to the server, return URL on login will always be the root of your SPA. E.g. suppose your SPA root is /app, and you try to access /app#/client when you aren't authenticated, you will be redirected to the login page, but the return URL will be /app and not /app#/client as the server has no way to know the hash part of the URL as the browser never sends this.
Not really supported design if you plan to make your your Web Api available outside your SPA. Imagine a console app trying to connect to your API?
So in short, the MVC view that we use to bootstrap our SPA is protected with [Authorize] as well as our Web Api methods. Inside the MVC view we also initialize our UserContext Angular service using Razor to inject whatever user properties we want to expose. Once the SPA is loaded via the single Razor view, everything else is handled via Angular.
We have used what Beyers described before and it works well for most apps, and I use it frequently.
In our current application we are working on the premise that separation of concern should apply to route management.
Normal lifecycle:
User goes to www.server.com
Server sends down index.html
Client makes request for minified assets (.js, .css., etc.)
Angular loads -- a directive removes the loading class from the body (revealing the login section)
The Angular LoginCtrl makes an autologin attempt. (Login and Autologin in an Angular service).
The server returns a HTTP 401
The login screen remains visible.
User successfully logs in ( server gives the browser a authToken cookie; angular does not know or care)
Angular sets some isAuthenticated variables in the BodyCtrl and LoginCtrl
The login section receives a class of .hidden and the content recieves a class of .visible (insert ng-hide/show animations for fun)
User starts filling out a form, but takes an obligitory, 30 minute phone call from relative.
Server has expired his session 10 minutes ago
User finishes and submits form but the server return unauthorized (401)
http-auth-interceptor intercepts the 401 from the server, caches the submit call and publishes a "login-required' event.
The BodyCtrl listens and sets isAuthenticated = false and then the ng-class and ng-show/hide do there work on the login and content sections.
User re-signs in and 'login-confirmed' event is published
http-auth-interceptor posts cached call.
User is happy
(the content section can also display some public views as our rest api has some routes that are made public -- displaying the public views is handled by a simple function similar to isAuthenticated)
Angular Ctrl structure:
index.html
<body>
<!-- I am a fullscreen login element, z-index=2000-->
<div data-ng-controller="LoginCtrl" data-ng-hide="isAuthenticated()"</div>
<div data-ng-controller="ContentCtrl">
<!-- fullscreen class has a z-index=2001 -->
<section data-ng-view data-ng-class="{fullscreen: isViewPublic()}"></section>
<!-- header and nav go here -->
</div>
</body>
We could get a little more creative on how display the public views/routes but you get the idea. We only have a few public routes and they are mainly for registration, password resets, etc.
Disclaimer: I have yet to integrate with and oauth/external authentication services. Hopefully this setup will still hold water.
Any critique of this process is welcome.
By no means am I familiar with Microsoft backends, but still I'll give it a try ;-) :
Good resources on how the authentication/authorisation should be done in Angular-based SPA:
https://github.com/fnakstad/angular-client-side-auth
live demo: http://angular-client-side-auth.herokuapp.com/login
As you requested there are 2 methods of authenticating:
own profile
external providers.
It redirects to the provider website though :-/
NodeJS on the backend
Good ng-conf talk on how authorisation is done in Google Doubleclick Manager application: http://www.youtube.com/watch?v=62RvRQuMVyg&t=2m29s
It's not quite what you want (authentication), but the solution begins to kick in on the authentication phase. Furthermore it may be useful later and the approach Ido is presenting seems really sound.
Slides: https://docs.google.com/file/d/0B4F6Csor-S1cNThqekp4NUZCSmc/edit
Last but not least: Mastering Web Application Development with AngularJS.
A brilliant Angular book by Paweł Kozłowski and Pete Bacon Darwin.
It has a whole chapter or two dedicated to auth- stuff. It shows some complex solutions, such as retrial and session-expired interceptors. But even if you will not use approaches from the book directly, those chapters are still a must-reads since they may give you an inspiration for devising your own auth- solutions.
Remark - http-auth-interceptor: As it is mentioned in the book, the securityInterceptor solution was originally invented by Witold Szczerba. See the blog post.
http-auth-interceptor code, mentioned by #CorySilva, is actually sample code to concepts explained in the post.
btw: Those 2 chapters are great, but I hope that the Community comes up with some easier solutions in the future. Every time I read this interceptor promise api-based code I get a severe headache :)
btw2: If somebody doesn't consider oneself an Angular expert, the entire book is definetly a must-read and great complement after reading the Guide
As for building the login page with ASP - I suggest using ASP only as a backend and middleware and drawing whole the app with Angular.
You can start with your approach and switch to the pure-Angular SPA if it will begin to require more and more crazy hacks to make technologies play together nicely.
But I might be wrong and this particular case won't require applying any hacks.

Resources