Load a secure page for API front-end website - javascript

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.

Related

How to store user data in browser more securely?

I'm working on a project where I'm verifying admin and user from the backend. I have a database and there is a collection called admins. I stored my admin's email there and when a user will log in if the user's email is available in the database it will return isAdmin true or else it will return false. so that's how I can give the admin special access. But the problem is I'm storing my user information in the local storage so every time when the user opens the browser I can get his info without login him. so I have to also store isAdmin true or false in the local storage. If anyone edits the local storage he can get access to the admin panel. I want to know how can I make it more secure or how can I store isAdmin more securely so that no one can edit it from the client-side?
so ideally you shouldn't really solve these issues on frontend side of application but on API (backend, db, whatever you use). Only this that should be somehow saved on frontend (client) is user's token and with every request to API you should include this token and backend should be responsible for authorisation of request.
Simple example:
user logs in to api
api responds with auth token - 'abcd1234'
client saves this token to local storage / cookie
in next calls you include this token to request
GET /all-users { headers: { Authorisation: 'abcd1234' } }
API reads this token, decides if owner of this token is authorised to access these data
It's not this simple in real life, but you should understand a little.
And now solution to your problem - i suggest you to do none of this, but for school project its okay i guess
store your role in some hash so user doesn't know what is under the hash and can't simply guess admin hash
use some UUID instead of role - basically same as 1.
store your role in some global variable - so this way users can't see them in localStorage or cookies -- but its on client so its accessible to everyone in source code

Is there any way that multiple users can upload to my Youtube channel via Youtube-api

I have used the Youtube-api and also created the oauth-clientId for some demo project. I also used the Client libraries (java & javascript) for uploading videos to my channel and i succeeded. But i don't want to share my login credentials and want my client users to upload videos to my channel. Is there any way, i mean documentation or procedure or youtube-implementations?
Assuming that you are using Java as you said. You should have a refresh token after your application has been authenticated.
The refresh token can be used to request a new access token. You should use this refresh token to allow others to upload to your channel. Note: To my knowledge you cant get a refresh token with the JavaScript client library due to security issues. You need to use a server sided language to do this.
For Refrence:
YouTube does not support service accounts so that wont work. API Key is only used for accessing public data so that wont work either.
I finally found an answer to my question and now my users[whom i give some authorizations] can directly upload to my youtube channel.
As per the comments i received for my question, i came to the conclusion that i have to do it at the server side because of the security issues.
The thing which came to rescue is namely Refresh Token.
I first created a simple application through which i logged & uploaded video [uploading is not necessary] into my youtube account and received the respected refresh token
Then i saved that refresh token through which i created a Credential object manually.
You can check the code provided by google :
UploadVideo.java
Credential credential = Auth.authorize(scopes, "uploadvideo");
This is what i replaced with this and obtained my own refresh token.Refresh token does not expire like normal access token, and is used to generate normal access token when needed. So, refresh token was the key to my question
Then at the backend, the only thing you have to do is just create the Credential manually. You can use this code
getCredential = new GoogleCredential.Builder()
.setJsonFactory(JSON_FACTORY)
.setTransport(HTTP_TRANSPORT)
.setClientSecrets(clientId, clientSecret)
.build()
.setRefreshToken(refreshToken)
// The refresh token here will be the same you received offline.
Here is the official google doc about this concept
Refreshing an access token (offline access)
Access tokens periodically expire. You can refresh an access token without prompting the user for permission (including when the user is not present) if you requested offline access to the scopes associated with the token.
If you use a Google API Client Library, the client object refreshes the access token as needed as long as you configure that object for offline access.
If you are not using a client library, you need to set the access_type HTTP query parameter to offline when redirecting the user to Google's OAuth 2.0 server. In that case, Google's authorization server returns a refresh token when you exchange an authorization code for an access token. Then, if the access token expires (or at any other time), you can use a refresh token to obtain a new access token.
Requesting offline access is a requirement for any application that needs to access a Google API when the user is not present. For example, an app that performs backup services or executes actions at predetermined times needs to be able to refresh its access token when the user is not present. The default style of access is called online.
Server-side web applications, installed applications, and devices all obtain refresh tokens during the authorization process. Refresh tokens are not typically used in client-side (JavaScript) web applications.

Website hold user details

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.

Is it a secure way to handle returning user in ember?

I am using ember to write a web ui for a site that requires user to log in. Suppose the browser has stored some cookie from last login of a user. Now the user visits the site again. So, is it a secure and common way for ember to log the user in automatically based on the cookie from the last visit? If so, what are the common ways to implement this? (I can't find anything from Google.) Furthermore, how do I create the cookie upon login? Is it a common way to just put a user id, password hash, and expiration in the cookie?
Additionally, any references related to this subject are greatly appreciated.
Edit 1
In light of Vohuman's answer, I think I can make my question a little more specific. Basically, what I want to know is a common and secure implementation to keep a user logged in, even when they close and reopen the browser. Namely, the life time is beyond the session scope. Take linkedin for example. If you are logged in and exit the browser. Then next time you revisit linkedin, you are still logged in automatically. Right now, what I can picture is a solution like the following.
When you first log in to the site, the server will return a cookie which includes an authentication hash token. Then next time when you revisit the site, the server will receive the hash token and thus authenticate your session.
So, is above flow basically what people usually do to keep a user logged in? If so, is the JSON Web Token (JWT) basically one way to construct the hash token I mentioned above? Additionally, assuming the connection is HTTPS, this approach seems secure to me. Is it not?
Edit 2
This article gives an interesting discussion regarding where to store the access token.
is it a secure and common way for ember to log the user in automatically based on the cookie from the last visit?
Yes and no. Security is a complex topic. Usually session cookies are used for authorizing users. This is actually the most used method of keeping the users logged in. If the user can't keep his credentials secure then any layers of security can be vulnerable.
For Single-page applications usually access tokens are used instead of cookies and sessions. The client sends the user credentials and server returns an access token. The token is encrypted and expirable and can be stored in localStorage or sessionStorage. Using JSON Web Tokens (JWT) standard is a popular method for implementing user authentication and authorization in web services. As an example, the Facebook Open Graph API uses access tokens.
JSON Web Token (JWT) is a compact, URL-safe means of representing
claims to be transferred between two parties. The claims in a JWT
are encoded as a JSON object that is used as the payload of a JSON
Web Signature (JWS) structure or as the plaintext of a JSON Web
Encryption (JWE) structure, enabling the claims to be digitally
signed or integrity protected with a Message Authentication Code
(MAC) and/or encrypted.
edit:
So, is above flow basically what people usually do to keep a user logged in?
For traditional websites, yes.
The whole point of using access tokens is keeping the web service/API stateless. This means that server doesn't have to store any cookies/sessions for authenticating and authorizing users. The stateless is one of the key factors of implementing web services that follow the REST paradigm. It's client that has to store the token and send it to the server (via the Authorization header or query parameters). The server doesn't store the token. Of course, you can store the tokens on the server if you want to add another layer of security, but it's not so common and not necessary. Storing the tokens on the server can also make your application vulnerable to database attacks and is not recommended.
If you want to make the process more secure you can decrease the validity time of access tokens (1 hour, 1 day or 1 week, it's up to you).
As for localStorage, is it secure?
localStorage data are stored separately for each origin (domain). A malicious user can only read the data if he/she has access to the user browser. You should make sure that your app doesn't have any XSS vulnerabilities so malicious users can't inject any scripts to your application. This is actually a different topic.

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