ParseUser.getCurrentUser() confusion - android

I'm using Parse as the backend.
To check if the user is logged in I use ParseUser.getCurrentUser(). What I don't understand is, if the user changes his password from somewhere else (another device, the web-client), will this ParseUser return with some kind of error?
I don't think it does a check on the server, so I think it just returns the last saved user. This mean that I can continue to use this user (with an old password) or will I get a "wrong credential" response on the first request to the servers?
If I don't get it, will I at least get it when setting an ACL with parseObject.setACL(new ParseACL(ParseUser.getCurrentUser()));?

Try same action on yahoo in 2 open browsers of different types and see what you get?
Each client's been handed a token value by the respective servers and until the token expire will not be prompt for a new logon.
Well IMO Parse work very similar except the lease on Parse token never expire.
Response to the original parse logon contain the token value which the SDK may retain. Details are in the docs section on Rest api / user logon...
So, if a diff client change password but the token lease over on some other client never expire, the other client stays logged in.

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.

What to do if token expired

I have communicate with API using retrofit. When the user is log in, I save account to database and when the user go to app next time, I get data from database (so I skipped login screen). Problem is when user's token expires.
How to handle the situation?
in login fragment
PSEUDOCODE
user = ... //get user from database
if(user != null) {
startActivityAccountActivity();
}
//onButtonClick
emailLogin();
Don't go to your "logged in" activity just because you have a token saved, because as you have correctly noticed, it may be invalid. Try authenticating with the API when you get the token, and only go to the "logged in" activity if it indeed worked. Otherwise proceed as if there was no token saved (and remove the expired one from the database).
You should also note that the token may expire when the user is in the "logged in" activity. For example, the user logged in, used the app and then went to another app from the recents screen. A week later he/she returns to your app with the "logged in" activity open, but in the mean time the token has expired and nothing will work. So you should also check if the token still works there, maybe in the onStart() of the activity.
As indramurari said, you can also handle it on the backend if you control it. But keep in mind that it doesn't solve your inherent problem of handling expired tokens, a refresh token may also expire and you are back to square one. If you make refresh tokens not expire you can just make the login tokens not expire. (This paragraph would be a comment on his answer, but I don't have enough reputation.)
It depends on your back end security level. You have two options to handle this situation.
Build some mechanism on back end side so that your server will send some refresh-token along with the user's token at the time of login to Android device. Whenever user's token get expired then request from Android device to your server to obtain new user's token by sending old user's token along with refresh-token. And you can use that new user's token for future. Repeat this whenever user's token get expired.
Note - refresh-token is for validating if it is valid resource who is requesting for a user's token.
You can delete the user account from database and tell user to Re-Login.

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.

Handling Sessions on Google App Engine with Android/IPhone

I'm starting to write an app whereby a mobile app (Android/IPhone) will communicate with the GAE backend (Python) through a series of Web API calls using JSON.
I can't use Google Accounts for authentication so I need to implement my own auth. I have an idea of how to do this, but I'm not sure if there is a better way.
Can anyone help with some code examples/suggestions of how to achieve the below please?
Method
Mobile app calls a Login method on the server which authenticates and creates a session key in the store and returns this to the app - not sure how to generate the key/session or where on the request/response it should be.
On every call, the app passes this key for the server to authenticate and allows the action if it passes.
User should not have to login on mobile again unless they explicitly logout or lose the key.
Login Method - without key generation
class Login(webapp.RequestHandler):
def post(self):
args = json.loads(self.request.body)
email = args['e']
pwd = args['p']
ret = {}
user = User.gql('WHERE email = :1', email).get()
if user and helpers.check_password(pwd, user.password):
ret['ret_code'] = 0
ret['dn'] = user.display_name
else:
ret['ret_code'] = 1
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(json.dumps(ret))
I think you should use features webapp2 providing to implement your custom registration.
from webapp2_extras import auth
from google.appengine.api import users
class RegisterHandler(webapp2.RequestHandler):
def post(self):
email=self.request.POST['email']
password=self.request.POST['password']
#Let webapp2 handle register and manage session
user = auth.get_auth().store.user_model.create_user('own:'+str(email), password_raw=password,email=email)
#user (True, User(key=Key('User', 80001), auth_ids=[u'own:useremail#mail.com'],email='useremail#mail.com',password=u'hashed_password',...))
if not user[0]: #user is a tuple
self.response.write(user[1]) # Error message
else:
#You can extend your User Model e.g UserProfile(User): or have a UserProperty in your profile model as the example.
profile=UserProfile(user=users.User(user[1].email)).put()
self.response.write(str(profile.key()))
class LoginHandler(webapp2.RequestHandler):
def post(self):
email = self.request.POST.get('email')
email = self.request.POST.get('password')
# Try to login user with password
# Raises InvalidAuthIdError if user is not found
# Raises InvalidPasswordError if provided password doesn't match with specified user
try:
auth.get_auth().get_user_by_password('own:'+email, password)
#Return user_session with User id,
except InvalidPasswordError, InvalidAuthIdError:
#Error
You can check user logged in by:
if auth.get_user_by_session():
#Logged in
else:
#Not logged in
On your client application(Android, IOS). You only have to store the response cookie and send it for every sub sequence requests.
Good luck :)
Have a look at webapp2 and webapp2 extras with sessions, auth and JSON
I cannot see why you would need a session?
Sessions on App Engine are persisted in the data store, so if you can keep your requests stateless, I encourage you to do so.
As you will have your own user service which will authenticate the users, I suggest you use Digest authentication, as the secret is never included in the request.
There are libraries implementing Digest for most client and server platforms.
If you dont explicitly want to use Sessions etc. you can simply use the Datastore. Try following this:
Get a unique deviceID/email to identify each unique user.
On request from a specific user, generate a random authentication key, and store it attached to the user's email/deviceID and probably the current timestamp and a loggedIn flag.
SO you have:
User email/id: someone#example.com
password: xxxxxxxxxx
Key : 2131231312313123123213
Timestamp: 20:00 12-02-2013
loggedIn : boolean value
This can be database model. Now whenever the user logs in:
Check email, password combination.
If valid, generate random key, and update the datastore with the new key
update timestamp with current time, and set loggedIn to True
Now return the key back to the client (Android/iPhone) in a JSON object.
Now on every request, Check the received key against the one in your datastore, and if loggedIn flag is set to true. If both OK, process the request.
Also, on Logout:
Just set the loggedIn flag in the datastore to False.
Hope this helps :)
Try gae-sessions for session management. It creates secure cookies for you and allows you to easily associate data with each user. Just provide your own logic for the initial authentication.
It was built specifically for App Engine and is pretty popular and super fast/scalable.
https://github.com/dound/gae-sessions
There are many ways to do this.
1) When you check the users login details if it checks out you can then create a random UUID or string and store the User object in memcache with the random string as the Key and the User Object as the value. Then return the random string along with your response headers. On the mobile when you are parsing the response, get this header and store it in the local cache. On all further requests keep sending this key back in the request header and in your controller get the User object from memcache using this key and proceed. If the object is not in memcache you can send back a response which prompts the user to log in.
2) If you dont want to use memcache you can store the User object in the session and on the client side while parsing the response get the session id from the response. Its usually JSESSIONID. Then store that and resend it with further requests. In the controller you can check if the current session has the user object else force login.
1) Another way to go would be to return the appengine key for the user along with the response and resend it.
Just google get response header from response. Then get the SESSIONID/JSESSIONID header, store and add the field with the same name and value to all further request headers. Thats the easiest way.
My first answer on stackoverflow and no code exapmles, dangit if only i knew python.

Design approach for login without auth token

I am writing an Android 2.2 app for my company. The app simply sends http get/put/post requests to perform certain operations. There is no real login procedure as the username and password have to be included in each http request.
I could see that there is AccountManager in Android. But since the username and password (instead of some auth token) are needed for each http request, how can it fit in? Obviously, I want to make it similar to other Android apps so that the user only needs to login once for the very first time and it won't prompt for username/password again when the app is re-launched.
Any suggestion is appreciated. Thanks!
I have developed an application like that, so here is how I solved it, in psuedocode.
But since the username and password
(instead of some auth token) are
needed for each http request, how can
it fit in?
1#: Make a first page, a login page. Let this View include two EditTexts (username and password) and one Button (login button).
2#: Make a login request on the Button click to see if you're getting a correct Cookie with HTTP header names that is corresponding with the values you are getting when you're logged in. Locate valid information via a network tool, like WireShark. For more information about the login procedure, check out my other answer here.
3#: If the username and password resulted in correct Cookie information, save the username and password in a SharedPreferences and make their values available through your application by assigning it into an Application class, read this for more info regarding global variables. If the values were incorrect and you did not get a valid Cookie, show it to the user via a message (Toast?).
4#: When you are trying to reach the authorized information, make a request by using the saved information in the Application class.
5#: Next time you're starting your application, make a check in onCreate() where you are checking if SharedPreferences contains user information, if so: see step 6#, otherwise wait for the user to start entering information.
6#: If the login page has determined user information, assign the SharedPreferences to the global Application state, finish the login Activity and start the authorized Activity instead. This will happen very fast, so the user wouldn't notice that the "login page" was displayed.
7# (extra step): In the authorized Activity, make sure to grab the user information from the Application instance. When doing the first request towards authorized content, validate the task as you did in step #3 in order to control if the user has changed the password on the website. If the user hasn't changed any information, start grabbing the response and you are free to do whatever you want.

Categories

Resources