I'm working on an android apps. I am using ionic framework. In some pages I need to get data from a web server and the result is an object json.
My problem is if some one arrives to GET the pages where I get the json data, one can fetch all my database data by changing the http request.
Is there any way that can improve security of my apps?
You should make some kind of authentication mechanism, for example, a token in the header, that way you know wether the user has access to that resource or not.
So when you make your request you can generate a configuration for that particular request.
Example:
var url = "http://yourserver.com/api/your/path";
var config = {
"headers": {
"Authorization": "Bearer someBearerFromTheServer"
}
};
$http.get(url, config);
The backend implementation for this to work depends on the language you use. Here google is your best friend.
A more advanced way to do this, is to use interceptors in the $http service and attach the token to the header in every request, but be careful, you should secure this so you won't send your credentials to every request you make (sometimes your app might need to request data from another server).
You can read more about $http services and its configurations in the $http service documentation.
Regards
Related
I need to develop an API for web as well as mobile with NodeJS as backend. Since, both have common endpoints --> I was wondering how to handle error cases like for e.g. --> if there is an error and user is on web I can do res.redirect and the user will be redirected whereas if the request was from mobile then I will have to set an 'action' variable which will guide the mobile app to take the next action for e.g. ask the user to login again.
app.get('/users/musicList', function(req, res){
// check with db.
// lets say there is some error --> the API token is not valid so user needs to
// login
if (req was from web) {
res.redirect('/signin');
} else {
var result = {action : 'SIGNIN'};
res.status(200).json(result);
}
});
Is this the correct way to go ? It makes code look a bit messy. Any suggestions.
An Easy way to do this is to have two different endpoints for mobile and web. (Wait I have two more solution).But this would result in code duplication.
web: domain/route
mobile: domain/api/route
Another way is to have only api/route which uses only json. And to handle the error and routing in front end. This works if you are using front-end frameworks like angular and using AJAX requests.
Third one is to check for the client need and acting as in your question. Check this link for how to determine what client needs.
NodeJS : Validating request type (checking for JSON or HTML)
I am developing a mobile app on Android.
I download a lot of information from the backend via REST API.
For example for obtain the information about a contract I use the api the following request:
GET /contracts/01212314.json
It return a json with many fields
{
"conto_contrattuale": "01212314",
"intestatario": "Dennis D'Amico",
"utilizzo": "COTTURA + PROD. ACQUA 7 GG",
"codice_settore_merceologico": "E1",
"settore_merceologico": "ELETTRICITA",
"codice_societa_vendita": "Z016",
"societa_vendita": "Estra Energie S.r.l.",
"fornitura_indirizzo": "Via Palermo",
"fornitura_civico": "20",
"fornitura_precisazione": "Rosso",
"fornitura_cap": "59100",
"fornitura_comune": "Prato"
"rid": false,
"fatt_elettronica": true,
"fatt_email": "andrea.bettarini#devise.it",
"fatture_scadute": 1,
}
But I am only interested to the field : "fornitura_indirizzo"
I can't modify the backend and the API.
So I think to create a new middle backend that fetch the info from the actual backend and exposes a call only for the field "fornitura_indirizzo".
How can I do?
Is it possible on google cloud platform? and is it free?
Thank you for your consideration.
You can put a file on your server that fetches the data en then recreates a partial array and echo that in json.
Example:
$contract = Json_decode("/contracts/xxxx.json", true);
$needed_info = $contract["fornitura_indirizzo"];
Echo json_encode($needed_info);
I can't access to the server and modify. I can only send request.
I apologise if I misunderstand your goals here, but why bother with creating this new back end for your app. You could simply call the existing back end and ignore the unneeded information. Either way, that existing back end has to send all that info somewhere for every request your mobile app performs. You're also adding more latency to the request since it has to go through your back end first.
I can see this being worth it though if your goal is to minimize the data downloaded by the mobile app when it does a request.
Hello all i am making an android app in whiich i have multiple account login at a time now my question is that i for multiple logins i should use sessions to verify every account user that is logged in. Now i am using express on the server side i have read a lot of documentation on storing sessions in node.js
Express-session (Though it is only good for development but not for production but not for my app)
Cookie-session
connect-Redis
connect-mongo
I have also heard about json web tokens where i can generate unique tokens and then i can pass the tokens to the client using res.json({user_id:"user1", token: "generated_token here"})
I have also heard about passport but dont know how it is going to do this also as in passport i use express-session by default will it be good for production or not ??
Now my first question is i have read all of there docs and nowhere it is mentioned where i am creating unique tokens for every user that is signing up.
Second question as i am using my server for android app there will be no use of cookie i will be sending user token as in parameter req.body.token now how to cmpare this with current user_id.
Actually i dont get the flow of control i mean how everything is going on in session in node.js. Also what is this secret is this thing generating unique tokens or what. Also i mean about 100000 of users are registered for my app now please tell me accordingly which way should i use for my app.
I have asked this question previously but there i did not mention that as i am not making a website how to do this(As in my case there will be no use of tokens)
I know this question i am asking is very vague but please bear with me i just want to understand how sessions are used in node.js
Thanks Anways
I'll try to answer this, but it is vague (as you pointed out). I'm going to make an assumption that your Android app is a native Android app and is going to be connecting to some sort of NodeJS backend in the cloud that is based on ExpressJS. If that's not the case, please clarify your thoughts in an update to your question.
The best idea for this specific scenario is to look to the cloud provide. Azure App Service Mobile Apps, for example, allows you to implement authentication - it eventually returns a JSON Web Token (http://jwt.io) to authenticate each request.
If you don't want to be beholden to a cloud provider, but want to run it yourself, you are going to have to implement the token generation and checking yourself. This generally follows the form:
Set up a WebAPI endpoint (maybe /signin) which takes whatever token the identity provider gives you, verifies the information and returns a JWT - there is an NPM module (jsonwebtoken) for producing the JWT. Ensure the JWT includes the identity of your user. I tend to use email address for the identity.
Your Android application will do a WebAPI request to your backend with an Authorization header, the value of which is "Bearer "
Your NodeJS API will use JWT authorization to validate the JWT and extract the user identity so you can use it in your API logic.
The important thing to note in this specific scenario is that your backend code is implementing a WebAPI - there are no cookies nor sessions in the API. The only thing that is linking the user from the client code to the backend code is the JWT.
As a short piece of code, here is how you verify a JWT:
var express = require('express');
var app = express();
var jwt = require('express-jwt');
var jwtCheck = jwt({
secret: new Buffer('your-jwt-secret', 'base64'),
audience: 'your-jwt-audience'
});
app.get('/api/protected', jwtCheck, (req, res) => {
// Your code here
});
app.listen(process.env.PORT || 3000);
i'm having a little problem with my phonegapp app on Android with python-django as backend. When i close the app i lost all the cookies that the server sets after the authentication (sessionid and csrftoken).
So, every time i open the app i have to do the login procedure. I try to save the sessionid in localStorage and then create my own header but this is not allowed by XMLHttpRequest specification. I need a simple workout for doing something like this:
function get_csrf_token(){
$.ajax({
url:"http://www.mywebsite.com/token",
type:"GET",
dataType:"text",
beforeSend: function(request) {
request.setRequestHeader("Cookie", 'sessionid=' + window.localStorage["sessid"]);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(JSON.stringify(XMLHttpRequest));
alert(JSON.stringify(textStatus));
alert(JSON.stringify(errorThrown));
},
success: function (token) {
window.localStorage["token"] = token;
return token;
}
});
}
Is this possibile with phonegap or i have to login every time i start the app?
You really aught to be using a different authentication method when dealing with mobile. It's a lot easier to try token-based authentication. Essentially you have a form on your mobile app that takes their username/password and pass it to a view you design that ensures validity and then responds with a token that the app can include in all subsequent calls.
You can implement this in Django fairly easy with a custom authentication backend, or you can use Django Rest Framework http://www.django-rest-framework.org/api-guide/authentication#tokenauthentication that has it built in.
What you're doing is definitely possible. It's impossible to set cookies on an XMLHttpRequest object. But if you set the cookie using document.cookie first, it will be sent on the cookie header for every subsequent request.
function get_csrf_token(){
document.cookie = 'sessionid=' + window.localStorage["sessid"];
$.ajax({
url:"http://www.mywebsite.com/token",
type:"GET",
dataType:"text",
...
});
}
The only thing you are going to want to watch out for while doing this is the possibility of an XSS attack. By storing the session id in localstorage, if your app were to have an XSS vulnerability, an attacker could possibly get the localstorage session id and send it to their server using JSONP or an image tag etc. Since you are using phonegap, you can mitigate this problem by using a whitelist policy that will only allow requests to go to your known servers.
In my asp.net mvc4 project, I am using ApiControllers to serve both web clients and mobile clients. To secure the web services, I am using the [Authorize] annotation.
So for now, the web client is working fine. However, when I tend to invoke some Web API from a mobile application (e.g. Android), I got an error.
when I looked back at code snippet:
[Authorize]
public List<double> GetSomeInfo(int param1, string param2)
{
User user = SessionData.CurrentUser;
// do something using user.UserId
// ....
}
Session Data does hold user connected properties only when he is connected to the Web App. But in the case of mobile clients, Session Data is null. So, is there any appropriate method to resolve this problem.
In my opinion, I think that userId should be provided as a parameter for any Web API that may need it to do achieve some treatment.
What do you think ?
You are talking about two different things :
Session
As Darrel said, Web Api was not design to support Asp.net Session. HTTP and Rest Services are stateless – and as a result each HTTP request should carry enough information by itself for its recipient to process it to be in complete harmony with the stateless nature of HTTP.
So, do not rely on Session Variables, but add more paramters in your request.
Of course, there are a way to use session in Web Api, I suggest you to to use it.
Authentication
Because working with only paramaters ( such as UserId, AccountId, ...) is not very secure, you have to use Authentication and Authorization. I highly suggest you to read the security section in asp.net web api web site. Web Api support many authentications (Basic, OAuth, Windows, Custom, ...). You have to choose what is the best for you.
Web API was not designed to support sessions as they are a HTTP anti-pattern. You can get the currently authenticated user by accessing Thread.CurrentPrincipal if you have setup the necessary authentication mechanisms.