Website hold user details - javascript

Using angularjs in the client , and c# in the server side.
I want to learn how can i create a website with users.
I know how to store the data in the db.
My real question is how the site remember the user session
After refreshing.
So the user dont need to login again.
Thanks guys.

Microsoft created a JWT (JSON Web Token) package for .NET Web API projects specifically for this purpose. And since you're using Angular.js, working with JSON is perfect.
There are plenty of tutorials for understanding how JWT works and securely saves a user's session like this one: https://scotch.io/tutorials/the-anatomy-of-a-json-web-token.
The idea is that your server sends your client/user a long encrypted string. The client saves it in their cookies and sends it to your server whenever you want to verify the user.
Most of the complicated details regarding encryption you don't need to worry about. Just follow the tutorials for setting up the exchange of the JWT tokens.

Back in the days, we use cookies to do this.
In the Restful html5 world of today, we can use several other options.
Websql, Localstorage, IndexedDB.
Probably you are using something like JWT to store an authentication token you use to make authenticated api calls.
The way to go, or as i do is store that token in localStorage and then, inject in every call to the api.
Then in the angular run section i check if the user is authenticated checking if i have the token stored, and if is not, send to the login page.
angular.module('Scope', ['ui.router', 'ngStorage'])
.run(function($localStorage, $state){
if (!$localStorage.authenticationToken) {
$state.go('login');
}
}
});
In this example, every time the app reloads, angular execute the run function, and checking if we have stored the token, if is not, send the user to the login webpage.

Related

Best way to protect frontend pages with Json Web token?

I'm working on a website where the user needs to log in to view the content. I'm working with react for the frontend and i'm using node to develop the API. I'm trying to protect my pages with a json web token, this way once the user logs into, the server gives a jwt which the frontend asks for to let the user to continue navigating or otherwise redirecting him to the login.
I know the server needs to verify the token, and i know i can create a middleware and implementing it to my API routes to achieve this. But my question is, if in the page i want to display i don't need to call any API route how can i verify the token?
I mean, should i create a route only to verify the token? or there is better way to do it?
Any suggestion or code example is welcome.
I suggest to use backend for token verification it is easier to manage in long run and safer. For example , if you use hmacsha256 signature , you have to leak your private key to client side for token verification. For client side identity verification, i suggest work with server side rendering instead to limit access to the protected part of website.

Load a secure page for API front-end website

I'm completing an unfinished project someone else worked on and trying work out how to create a secure page for an API driven front-end.
When a user logs in successfully, a local storage variable is being created that contains user information, including user token and user secret.
I require a secure dashboard page that calls secure API's.
Am I correct in the following approach :
When secure page loads, a JS routine is executed which checks local storage for user token. Can this be a simple check for user token existence ?
If token present then the secure API's are called using the secret key. The api then returns sensitive data to populate table.
Will this work?
UPDATE:
Both server and client will run under https. As data in encrypted, secret token can be stored on client. Front-End is static html/JS making API calls for sensitive data using secret (only available to authenticated user). None of the user data is hardcoded to F/E but instead is referenced from local storage. Then tokens can be used securely to make further API calls as required for sensitive data. So basically, no-one else should be able to get to sensitive data as cookie/storage is limited to client machine and will expire anyway.
I was looking for a blog/tutorial to confirm my understanding as above.
Thanks
This approach seems OK. I don't know your exact requirements, but I would suggest using a cookie instead of localstorage, given that the token is sensitive information and should not be stored for a long time if it doesn't have to.
If the user has it's personal permanent access token go with localstorage. If the token is fetched from an auth-server upon login, use cookies instead.

How to use JWT for a proxy server written using Node.js?

This is absolutely a newbie question & I am Node.js beginner.
I am not sure, this is right place to ask this question. But I may need idea from this large community. So let me explain what I am trying to do.
Server Configurations:
Node.js - 4.0.0
Hapi.js - 10.0.0
Redis
Scenario:
I am writing a proxy server in nodejs using hapijs. My Backend is ATG based e-commerce website and my api's are going to be consumed by web browser, mobile app etc..
We planned not to send the cookies sent by ATG to both browser and mobile.
So to maintain sessions and cookies from ATG,this is how we done POC.
First We planned without considering storing the anonymous user cookies returned from ATG. So we have done two POC's.
(Many of us know, what anonymous cookie is,any way let me explain that, if I put that one word -- Guest Checkout. There are many ways to accomplish this. But my Commerce Backend is implemented like this, When we go to website, you add items to cart and checkout that items without logging in right ? This what happens on background whenever we add the items they are only stored in your browser cookie,it not stored in persistent database, in any case user wants to login/signup to the account that cookie is retrieved from the browser and stored in database (basically that anonymous cart is transferred to logged in user.))
POC-1 (Not Considering Guest Checkout):
To access my api, user must be logged-in, after the successful login, We generate a rand-token and store it in Redis db associated with the cookies sent from the ATG for logged-in user and set ttl for 1 hour and return that token to the client
Now whenever they invoke any of api methods, they should send the token in the authorization header, I will check for token validity and expand the ttl once again for 1 hour and retrieve the cookies associated with that token, set that cookies in ATG request options and make a request.
3.On logout, I will clear the cookie and delete the token.
I have successfully implemented JWT fot this scenario, by generating a JWT token with user logged-in information in jwt payload. Used hapi-jwt-auth2.
POC-2 (With Maintaining Guest Cookies),
My API Will have endpoint /auth/generatesession, which in turn will return a 64 byte random token (we are using rand-token npm module for that) which will expire in 24 hours.
All the methods needs that access token passed back to me in authorization header and I will extend that token ttl to 24 hours.
Now they can invoke any api methods, like addtocart or something, even after adding items to cart , suddenly they want to login or something I can use their guest session cookie and transfer that cart to persistent database after successful login.
Questions:
Should I use JWT for the second scenario? If so,
How can I implement JWT for the Second Scenario? (Coz, don't know about who is the user?)
Does anyone think this is good idea for writing proxy server like this?
How can streamline session expiry of this token with ATG session Expiry?
Does anyone of using Node.js like this? How does it scale ?
If anyone care to give me an idea how to write this proxy server, it will be much helpful for me.
I Apologize, if this is too long question, just my way of explaining things.
Thanks in advance.
Sure, why not?
You don't necessarily need a user. A JWT stores arbitrary data, the username can be blank or anonymous. If a user logs it, and provides a token associated with a guest cart, then it can be assumed that that user is allowed to claim the contents of that cart, and the anonymous cart can be destroyed.
Sure, this is quite common (disclaimer: I've worked on something very much the same as you).
TTL is reasonable, but I have no idea what ATG is or how it handles it.
Yes. It scales very well as long as you ensure your servers are stateless, and that you manage all your state through something like Redis.
Too broad of a question, I would just use Express + Redis/Mongo/Postgres.

Ionic authentication for login with angularjs

As ionic uses angularjs, for login system there isn't any browser to save cookie or session in order to authenticate for each part of application.
One way is protecting by using this in app.js:
$urlRouterProvider.otherwise('/login');
Because any one doesn't access to other links into application. When returned answer from server (mysql database) is true , we can use this:
$state.go('app.main');
Is this a good idea? Or any other ways?
Since ionic essentially calls to a back end api, you can implement any standard api authentication mechanism.
The most common was would be have a toke based authentication, High level workflow can be as follows
1 - ionic app calls a backend server end point and get a token (by passing some kind of an encrypted key)
2 - Back end server generates a token (ideal for a given time period) and sends back to the ionic app.
3 - There after, in every request ionic sends the token. (ideally in the request header)
To save the token temporary , you can use a simple storage solutions like
ng-storage or sqlite
have a read here
For our company app we use a digest access authentication(https://en.wikipedia.org/wiki/Digest_access_authentication) with our ionic app and our node server that is hooked up to a sql database. Once the user is authenticated we send them a jwt (javascript web token). We can then store that webtoken locally (if they check the option for auto login) or they can re-authenticate whenever the app is reopened and we give them another web token. This has so far proven to be a safe and efficient method of user authentication. Here is a tutorial for using json web tokens and angular. http://www.toptal.com/web/cookie-free-authentication-with-json-web-tokens-an-example-in-laravel-and-angularjs
I would strongly encourage you to checkout John Papa's ng-demoes, especially one with JWT token, because that is what you want to use nowadays. (Those are not specific to ionic, but rather for angular.js apps in general)
basically you have several things you need to do:
handle all the places where you need to check if user is authenticated or not and emit unauthorized event
handle event and redirect to login state/route
In above example you basically add interceptor (https://github.com/johnpapa/ng-demos/blob/master/ng-jwt/src/client/app/services/authInterceptor.js) which looks if any request to the web services failed due to not authorized and rejects the promise returned by $http request
Also
As ionic uses angularjs, for login system there isn't any browser to save cookie or session in order to authenticate for each part of application.
You indeed can use localStorage/sessionStorage to store token and add that token to all requests. That is why you better off having token based auth for your web services, rather than cookie based. (basic auth can do to, just more cumbersome)

Chrome extension / web app session control

I am creating a chrome extension, rather a chrome webapp. This application just contains the html, js, image and css files. The application connects to a server to fetch data. I chose to do this as it would reduce the amount of files downloaded by the user. Using Backbone.js I have an MVC architecture in my application. Thus the application just sends json.
Now having said this, I need a session management. I plan to use Google authentication as the organization has Google Apps. I need a method that once the user has logged in using google auth the server get the user name every time the application makes a request.
Is it a good idea to add the user name in request header, if possible. Or should I use cookies? Can any one tell me how I could go about using cookies in this case?
This might be a late response but I want to present a more elegant solution to you given that the user has cookies enabled in their browser.
First read my answer on another question.
Now that you can send cross origin xhr from your content scripts all you need to do is store all your authentication and session management at server only. That is right, you just need to display whether the user is logged in or not and a logout button at client based on server response.
Just follow these steps.
At client Whenever user accesses your chrome web app, blindly make XmlHttpRequests to your server without worrying about authentication, just keep a tab on response from server which I describe below.
At server whenever you receive a request check for valid sessions or session cookie. If session is valid send proper response, if not send error, 401 or any other response to communicate to your client that session is not valid. It is better if you send an error code like 401 since then you can put a generic script at client to inform them that they are not logged in.
At Client If response from server is proper, display it, else display login link to your website.
IMPORTANT: Display logout button if user is logged in.
Check out my implementation of this in my extension
For help using Google authentication in your app take a look at Google's OAuth tutorial which comes with all you need (took me no time to set it up using this).
As for session management. The implementation of OAuth used by Google stores the tokens in localStorage. Also, as briefly mentioned in the extensions overview we are expected to use localStorage to store data. Thus, I suggest you store the users name here as it will be accessible throughout the app's lifetime (until it is uninstalled). However, you may need to manage the name stored here and consider what should happen when users log in and out. That said; I'm not sure if sessionStorage would be a better option as I've never used it before, let alone in an extension.
Note
localStorage and its counterparts only store strings so I suggest using a wrapper which uses JSON to parse and stringify to get and set your values respectively.

Categories

Resources