Access database in Cordova - android

I am very new to cordova developing. I am trying to develop one login page in android app, i need to access username and password from database for checking credential. Now i am hosting one web service and just pass the user name and password to that service using ajax request and proceed based on value returned from webservice. I dont know is this the correct procedure?. I am sending user name and password through ajax post, i think its insecure.Can you please suggest the best wasy to access database in cordova? I am using visual studio IDE for developing. I used following code to send username and pwd to webservice.
$.ajax({
url: 'localhost\service\Controller',// hostedd in iis
data: JSON.stringify({ username: 'user1', password: 'pwd' }),
sucess: function (data) {
//perform operation for login success
},
error: function () {
}
})
Thanks

Follow these steps:
If you use external urls, then white listen them:
http://cordova.apache.org/docs/en/dev/guide/appdev/whitelist/index.html
Use only https.
Verify the footprint of your cert by using this plugin:
http://plugreg.com/plugin/EddyVerbruggen/SSLCertificateChecker-PhoneGap-Plugin
Don't send the password, send the hash of the password. Use the same algorithm which you use in the backend for creating the hash.
Create a device UUID, save it on the device and send it to the backend and save it the first time, the device called the backend. Use this UUID for logging the device activity.
On every request to the backend, send the device UUID and check it.
Make sure, that you have a way in the backend to stop the activity of a device and user.
In some of my apps, I use the device UUID for individual encryption.
If you want, you can encrypt your whole app by using this plugin:
http://plugreg.com/plugin/EddyVerbruggen/SSLCertificateChecker-PhoneGap-Plugin
In some of my apps (B2B apps), I use an authorization which is working via QR code. In the backend I create some individual «secure Infos» and show them as an QR code. In the app you have a barcodescanner which scans the info , which is then saved on the device. Works great and this is a good way to have individual keys on the devices.

Related

How to securely send passwords between Android client and server side application?

My current Android application requires users to login with Username and Password.
The Android application calls a REST web service for user login and I do not want to transmit the password as cleartext.
How do I go about securing my users passwords so that the server side can Identify/authenticate each user?
I am currently trying to employ the Jasypt library as follows:-
ConfigurablePasswordEncryptor passwordEncryptor = new ConfigurablePasswordEncryptor();
passwordEncryptor.setAlgorithm("SHA-1");
passwordEncryptor.setPlainDigest(true);
String encryptedPassword = passwordEncryptor.encryptPassword(userPassword);
...
if (passwordEncryptor.checkPassword(inputPassword, encryptedPassword)) {
// correct!
} else {
// bad login!
}
however my server side is written in .NET and as far as I understand the Jasypt documentation the password encryptors employ a random salt.
How can I have my server side code match the hashed users password I am sending it?
All my webservices have HTTPS endpoints, does this guarantee that no one can "see" my users passwords "in flight" when exchanging for an access token?
If you use Https(TLS) then your password is inaccessible to anyone intercepting the network.
You should hash the password string in your server side code not in the client
Also you can use OkHttp CertificatePinner to pin Https(TLS) certificate to your connection for avoiding man in the middle attacks.
A good solution would be to avoid using the traditional Email/Password approach to authentication and go with what another answer here suggested of OTP or One-Time-Password.
Consider the user experience: typing an email and password on a mobile device is cumbersome and annoying and awkward. Then they have to remember their password as well? The average person in the Western world probably uses 10 to 15 apps per day and we want to tax their human memory banks for another password to awkwardly type onto their phone while they are on a packed subway train?
Although it's deceptively challenging to put together, consider One Time Password. With it, a user enters in a phone number as an identifying token.
In theory, every single user has their own unique phone number and thats easy for a user to remember. Since your user is on their Android device, makes sense so far, right? And no awkward typing of email and password.
After they enter their phone number, we then text them a code to the mobile device, which is a 4 to 6 digit number. The user enters that code in the application, thereby proving they are the owner of the device that the phone number is tied into.
The benefit of OTP over Email/Password is that it requires very little memory on the users part. And yes, it's even better than OAuth because what if the user never signed in to a Gmail account or Github account via their mobile browser? Then they are back to Email/Password awkward style authentication for mobile device.
One-Time password is user friendly.
But you say okay, but is it secure and more importantly to the question: How can I have my server side code match the hashed users password I am sending it?
Right, so One Time Password technology is always an ambitious project to undertake IMO.
So we need to persist the code that the user should be entering into the device so we can compare it at some point in the future. When you generate a code, save it to Firebase so at some point in the future you can reach back out to Firebase and say the user with phone number 212-555-1212 just sent you the code 1234, is that the correct code?
So, the way Firebase works with OTP is you can store the code in Firebase. The challenge though is actually texting the user a code. This is an actual SMS message. To handle that, you can't use Firebase alone, you can integrate the extremely popular Twilio. Twilio is all about interacting with users via phone SMS messages and so we can make use of Twilio to text the user a code.
You can also take care of authentication or user system inside of Firebase. Once the user enters an OTP, we generate the JSON Web Token through Firebase.
So all the JSON storage and all the info that reflects who the user is, all that can be saved on Firebase.
But there is another part to that question I have not answered:
How do I go about securing my users passwords so that the server side
can Identify/authenticate each user?
Okay, so you need to compare the code on some server. It can't be Firebase because Firebase is simply a datastore, it is a place to store JSON data, it does not give us ability to run custom code.
So do you write a server for the comparison of codes? We do NOT want to do this comparison on the user's device.
So what do we do? Also, how do we generate a code? Don't use the user's device for that either.
So where do we generate the code? We know to use Firebase data storage to store the code, but how do we generate it?
That's a good job for Google Cloud Functions.
So Google Cloud Functions are code snippets that run one time on demand on Google servers. GCF have tight inter-operability and integration with Firebase data stores.
We can add some logic or processing to the data sitting inside of Firebase. GCF will allow you some custom logic to generate your codes and save them to Firebase and GCF can also compare the code once the user sends it in.
AWS Lambda and GCF are nearly identical in functionality so that could be an option as well.
You have to be careful about what you do. Consider implementing a common two-factor key-sharing algorithm, such as TOTP.
A pretty uncommon, but really good practice, is the client-side hashing. This of course doesn't stop the hacker from logging in to the user's account, but it stops them from obtaining the potentially reused plain-text password.
I recommend that changing E-mail and password are done under the reset password formula, such that E-mail/SMS confirmation is required. And finally, as you do it is extremely important that the connection, where the login happens is secure, for example, https/tls.
There are couple of things you need to consider while implementing authentication and authorization between client(Mobile app) and server.
Firstly, what authentication and authorization mechanism does your server have to request api endpoints? (Is it Two-Factor Auth? Is it bearer token (grant-type username and password) based? Is it bearer token (grant-type access-token) based?
Secondly, as you have mentioned server programming is .Net based but can you be more specific whether your service layer (Api ) written in WebApi 2 or OData ?
Finally, does your server allow to communicate with or without SSH i.e. HTTP vs HTTPS? If it's with SSH then its okay to transfer user credentials i.e. username and password over othewise it will be never secured to transer credentials over HTTP.
Then only it comes at your end i.e. in Android Mobile App to impelement the authentication and authorization mechanism as per server requirement to communicate with api endpoints.
For example, my server requires to implement token-based authentication (bearer token and grant-type password) to make every server request (GET, POST, DELETE, PUT) and I have implemented using retrofit client as like :
public Retrofit getRetrofitClient() {
// first add the authorization header
OkHttpClient mOkClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder()
.addHeader("Authorization", "XXXXXXXXXXXX")
.build();
return chain.proceed(newRequest);
}
}).build();
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.client(mOkClient)
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
.build();
}
return retrofit;
}
and my service is
public interface LoginService {
#POST("/api/token")
#FormUrlEncoded
Call<TokenModel> getToken(#Field("username") String username,
#Field("password") String password,
#Field("grant_type") String grantType);
}
Now I can use this token in every request to commuicate with server. I don't need to transfer username and password over public internet rather I use just token and it has 24 hours expiration ( as server has implemented this token expiration date).
Hope it helps you to understand the authenticaiton and authorization mechanism between cleint(Android Mobile App) and server.

Mobile App webframe Authentication with Rails Devise

I am currently working on implementing a mobile app for our site that uses Ruby on Rails and Devise. The idea here is, at first, create a mobile login form that on successful login opens a web frame that is authenticated and allows the normal use of the (mobile optimised) site. Theoretically that should be possible.
I am having trouble with the following issues:
How do you get the pure session key for the user session via a json request? What methods can be used to manually generate it from devise, something that the sign_in(:user, user) method does?
Is it even possible to take that key and put it into the browser cookie the way it normally happens in devise, but on the mobile side?
I know that this is not the standard method of making mobile applications for the site, but I believe it should be possible.
You might want to consider using Devise Token Auth and treating your mobile application like just another webapp that requests permission from your main site. DTA is particularly nice since it takes care of managing the session tokens (renewing/expiring) and passing them onto the app requiring access. The issue is overriding your session controllers so that it automatically logs in after you already log in on the mobile app (or just rewriting your log in so it occurs in conjunction with the Rails site, rather than before). Considering you're already using Devise, this may also be more refactoring than you'd like.
If you want to put your authentication form on the mobile UI and pass the credentials over to the web frame, you need a way to pass data from the mobile app to the web frame.
How you accomplish this depends on what platform you're building on. I'm not really a mobile developer so I don't know for certain how difficult / easy these options are:
When opening the web frame, instantiate it with session data
Find a way to call methods on the client from the web frame. Something like getSessionData.
You could generate a fingerprint for the web frame, have the mobile UI send this data to the server, and then have the web frame authenticate with the server by sending the fingerprint.
Again, I'm not entirely sure how possible all these options are.
You should use token authorization and Android deep linking. It will allow you to login in the web browser and send a token to your app via deep linking.
OK, so I decided to make a webframe solution as follows, basically you post the login and password to a certain sign_in method specially designed to generate one-time sign in tokens for the application. You need two methods in the system to do that:
routes.rb
devise_scope :user do
get "sign_in_with_token/:token" => "sessions#sign_in_with_token"
post "get_login_token" => "sessions#get_login_token"
end
sessions_controller.rb (don't forget to add the method that increases the failed_sign_in_count on wrong password, otherwise that can allow brute force attacks)
def get_login_token
user = User.find_by_email(sign_in_params["login"])
password = sign_in_params["password"]
if user and user.valid_password?(password)
token = SecureRandom.hex(16)
user.update_attribute(:authentication_token, token)
render json: {token: token}, status: 200
else
render json: {error: "error"}, status: 403
end
end
and the method to sign in with that token
def sign_in_with_token
#user = User.where(authentication_token: params[:token], email: Base64.decode64(params[:email])).first
if #user
#user.update_attribute(:authentication_token, nil)
sign_in(#user, bypass: true)
end
redirect_to '/' # or user_root_url
end
That way the mobile app will work like this:
use the generic web frame to send ajax requests to the server and get that token for the user email if password is correct.
make a /sign_in_with_token/#{token from ajax}?email=#{base46 encoded email} link inside the app.
open that link inside the web frame and use the app as though you were logged in normally. Now the app can save email and password locally and use that logic to get the token again for another session. Later logging in will also be able to set the app id so that push notifications can be sent.
Appreciate any feedback or criticism on this solution.

react native android oauth2

I am developing a react-native application, in this application im trying to authenticating using oauth2. Now im trying to use a webview to retrieve my redirect_uri credentials, but im unsure how to retrieve it in react-native on a Android device.
I have found a example but it doessnt explain how to get the acces token in a variable, and I dont know how to implement this inside react-native.
for this purpose I am trying to use a implicit flow.
Grant Type: Implicit
The implicit grant type is used for mobile apps and web applications (i.e. applications that run in a web browser), where the client secret confidentiality is not guaranteed. The implicit grant type is also a redirection-based flow but the access token is given to the user-agent to forward to the application, so it may be exposed to the user and other applications on the user's device. Also, this flow does not authenticate the identity of the application, and relies on the redirect URI (that was registered with the service) to serve this purpose.
The implicit grant type does not support refresh tokens.
The implicit grant flow basically works as follows: the user is asked to authorize the application, then the authorization server passes the access token back to the user-agent, which passes it to the application. If you are curious about the details, read on.
https://www.digitalocean.com/community/tutorials/an-introduction-to-oauth-2
Integrate oauth2 with native (iOS/Android) mobile application
My question is what should my redirect_uri be?
How can I retrieve the variables on react-native Android?
Is 'implicit flow' the way to use on a mobile application?
First you start looking which oauth2 flowtype is the securest one for your application in question by looking what other recommend.
After that I looked at 'implicit versus password grant_type' and looked up the fields which are required:
https://www.rfc-editor.org/rfc/rfc6749
I made sure a authorized endpoint is active for testing (by making one active yourself with the correct grant_type) Next I wondered how to fill all the fields. By installing postman, i could analyze and make a POST call myself.
After that you look up your url which in my case was : localhost:8000/oauth/token
and post against it using postman.
I was stuck on the part that you can't use JSON on the request body, but instead the oauth request needed to be in 1 long parameter called 'body' as a string. This is the way a httprequest works.
//authorization grant type: Resource owner password-based.
const HOST_ADRESS = "192.168.104.137:8000"; //change with your own host
const client_id = "jpijpijpijpijipjipijipijipijipj";
fetch('http://'+HOST_ADRESS+"/oauth/token/", {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Cache-Control': 'no-cache'
},
body: "client_id=sfjwepifjpfweijgpeijSGIOEJOPGIWSJA35340537530708&grant_type=password&username="+username+"&password="+password
})
.then((response) => response.text())
.then((responseText) => {
console.log(responseText);
//redux succed do something.
//dispatch(actionsCreators.succesLogin(responseText));
})
.catch((error) => {
const data = {error: "A error happened"};
//redux error.
//dispatch(actionsCreators.errorLogin(data));
console.warn(error);
});
Hopefully someone else learns something coming across the steps I took.
Only need to save the token somewhere in a database to check (sql lite ) or realm.io (yay for next steps.)
First, you should choose the right grant type based on where you are trying to log in.
If the service is yours, you can go with grant type password.
If the service is third party, you can use implicit type. You provide redirect uri, which has to be registered with that particular service and which is used to redirect user after he is authentized.
Finally, there is a network API in React Native where you use fetch (see docs). As a second parameter to this function, you can provide additional informations and header. This is where you set all the required informations provided in the oAuth2 docs.
This is a very interesting example: https://github.com/bartonhammond/reactnative-oauth-hapi

Is Captcha good solution for android authentication?

I'm developing an application (as a part of team) for android that interacts with server (asp.net web service) for synchronize and update information in client side.
for preventing attack to server we use SSL connection and also authenticate users with soap header message contains username and password.
here is the scenario for synchronization:
users send web service request with header contains : username , password , time of request , and(for preventing man on the middle attack) hash code of all three parameters(username+password+time) as message signature
web service check that :
is this a new message by checking the signature of message stored in server
if this is a new message (and its not duplicated) then check that signature is true by hashing all three parameters(username+password+time)
then check expiration time : is the message new ( in 5 minute ) for expiring old messages
Authenticate username and password
validate datatype and length of parameters ( in this case only time of device's last sync )
response to request
device get the response as xml file
the question :
because of this scenario we have to give user's devices authentication information so they could interact with server in future and also we don't want to get any information like username and password from users ( for user experience purpose! )
so we build a Web Handler Captcha in server and when users are new, we send them a captcha image generated by their device code(it is uid generated by device something like : https://www.server.com?appid=00000000-0000-0000-0000-000000000000 ) and when if user sends the correct captcha to server we add a new user to our database ( auto username and random password ) and save to the android's account manager for future use
in your opinion is this a good approach for authentication and security?
Thank you for tips
Https and a method to get a sessionId is enough security for most apps, anyhow my opinion:
Unless you include a secret within the hashed variables a "man in the middle" can change the parameters and forge a valid hash.
I would recomend a registration method. It's going to take device information as parameter, and the captcha if you will.
It's going to return a deviceId and a deviceSecret. The deviceSecret must not be transmitted again, just used as part of the hashes.
Also consider using a counter instead of time. It can help against replay attacks and it's easier overall.

How to implement server side sessions in node.js with express for an android app?

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);

Categories

Resources