android app authorisation - android

I am making an application in android. How to do role authorisation in android. is there any package. please let me know.
Thanks,
NVN

I never used the Authenticator class. But if you plan to role your own authentication system, its pretty simple. Here are some tips:
Authenticate over https
Create a webservice that accepts username and password.
Once succeeded, save a token or
something in preferences so the app
knows it is authenticated.
I recommend using an oAuth
implementation because it is the most
safe. (Don't store email addresses,
instead use tokens)
Let me know if you need any other help.
Edit:
There isn't a library out there does this for you. You have to create a class called Token or User:
class Token{
String token;
Role role;
User user;
}
Role can be an enum like enum Role{admin, publisher, writer, reader,...}.
Then let's say you authenticate against https://foobar.com/REST/authenticate/?user=foo&password=...
Which returns a simple JSON or XML (I suggest JSON)
{
token: "12345667",
role : "publisher",
user : { userId : "amir", ...}
}
So now you make an HTTPS call and authenticate against a user and password. Then parse the json and create a Token object. Store this token object in the app and you should have everything you need.

Have you looked at the default Authenticator class? Here's the API from Google I hope that helps. =]

Related

Verifying user credentials with REST API?

I've set up a REST API on my site in order to return information from my database.
I'm implementing login and registration on my app right now. However, I'm not sure how to handle verifying user credentials (checking if an email is already registered, if a password meets its requirements, etc).
Since my REST API is not open to the public, would it be safe to pass the data like this:
/users/verify/email/{email_address}
/users/verify/password/{password}
Or is there a better (safer) way to do this? In other words, how can I authenticate and validate users when the login/register?
In REST you're talking about resources. A resource will have some state expressed through their properties.
With your example I would ask myself: "why verify an email", "why verify a password". Because you want to verify if a user can be registered.
So your resource will not be an email or a password but a user.
Verification is an action. Something which does not go well with a REST architecture.
What do you want to verify? You want to register a new user but also verify if he's allowed to register. So you'll try with some conditions to add a user to your collection of users. In REST with HTTP this can be done with a POST which acts like an add(User). The logic behind the request can then implement the verification rules on the user.
To post data just use the content body and use the headers for additional info. So I'd change my API to:
HTTP method: POST
Path: /users
Content-Type: application/json
Body:
{"email_address":"qsdfg#sdfgh.com", "password":"qlmkdjfmqlsk"}
Which simplifies your API to a single entrypoint for adding a user. Allowing or refusing to register the user can be communicated through the use of HTTP status codes and messages.
Of course sending passwords in plaintext is not a good practice but you can setup a secure connection with SSL or TLS to communicate.
Sending sensitive data in a URL is not a good practice btw. Servers can log the url which will show everyone with access to the log the password of the user.
The login is a bit different but not that much.
You'd need a resource which uniquely links a user to his conversation with your system.
HTTP method: POST
Path: /authentication
Content-Type: application/json
Body:
{"email_address":"qsdfg#sdfgh.com", "password":"qlmkdjfmqlsk"}
Response
Status-Code: 200
Content:
unique-id-to-my-user
The authentication could call your user api to enforce the rules and then generate the id.
You could use an OAuth2 implementation to handle this.
If your web service is Asp.Net WebAPI which will return an access token for the valid user, you can use Http POST request with username and password as body content.
For sample code, please take a look at my answer in the following question
Implementing Oauth2 with login credentials from native login page
For better security, use Https instead of Http.
Hope this helps!
You can use POST method.
/register with name, email, password for User registration
/login with email, password for User login.
Just make sure that you do not pass the password in clear. Perform some kind of encryption on it.

Google Cloud Endpoints custom Authentication

I am quite new to google cloud endpoints and I would like know how to Use Auth with Endpoints, the tutorial here is good, but I don't understand this thing:
It says, that I should add a user(com.google.appengine.api.users.User
) parameter to backend's methods for auth. If I want to use android as client part, I should provide GoogleAccountCredential object to make an authenticated call [2]. The GoogleAccountCredential is created this way
credential = GoogleAccountCredential.usingAudience(this,
"server:client_id:1-web-app.apps.googleusercontent.com");
credential.setSelectedAccountName(accountName);
The accountName is the name of a Google Account, so I assume, that everyone, who has the Google Account and is using my Google Cloud Endpoint application can create the GoogleAccountCredential object and make an authenticated call to backend.
But there are obviously many methods in my backend, which can be invoked only by some users of my app. (example: There is a method, which will give me a details about my friend, it's clear that this method can be called only by his friends.). Hence my question is: Is there any way to map the com.google.appengine.api.users.User to some my custom User entity, to be possible to check whether the User is really authorized to call the backend's method and not only to know that the method was called by a User with Google Account ? Should I write my custom Authenticator for this, if so, could you advise me how ?
Thank you!
You can set an Authenticator class which will handle the custom authentication.
https://cloud.google.com/appengine/docs/java/endpoints/javadoc/com/google/api/server/spi/config/Authenticator
you just need to set the authenticators param in the #ApiMethod and you can write your own authentication logic

How to fetch email id from LinkedIn android?

How do I fetch the email address from LinkedIn profile in my Android app?
You need to set scope with email permission. After that you will be able to recover that specific data.
private static Scope buildScope() {
return Scope.build(Scope.R_BASICPROFILE, Scope.W_SHARE, Scope.R_EMAILADDRESS);
}
Then use following URL to make GET request.
String url = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,public-profile-url,picture-url,email-address,picture-urls::(original))";
With this scope your ApiResponse will retrieve user's email.
Did you check the API documentation? From what I can see, there is no way to get the email ID from their API. My guess is that LinkedIn protects this particular information (as they should). If they allowed my personal information to be retrieved by anyone with access to the API I would likely get a lot more spam then I do.
I don't think you can access this information.
https://developer.linkedin.com/documents/people

Implement OAuth2 with resource owner password credentials on Android

I need to make calls to services which are secured by OAuth2 resource owner password credentials. I tried all the libraries on oauth.net/code, but with no success. All of them seem not to provide this kind of authentication, but seem to be great with 3 legged authentication.
My user should login with username and password, but I do not want to store username and password. I want to get an access token and refresh this token from time to time.
My network communication is currently based on spring 4 android and the resttemplate you can find there.
Any suggestions, which library I could use? I think this is a common problem.
I couldn't find anything either, so I've put together a library myself, and I am releasing it to the public.
Usage:
import org.sdf.danielsz.OAuth2Client;
import org.sdf.danielsz.Token;
OAuth2Client client = new OAuth2Client(username, password, app-id, app-secret, site);
Token token = client.getAccessToken();
token.getResource(client, token, "/path/to/resource?name=value");
With this grant type, the client application doesn't need to store the username/password of the user. Those credentials are asked once and exchanged for an access token. This token can then be used to access protected resources.
To check if a token has expired:
token.isExpired();
To manually refresh a token:
Token newToken = token.refresh(client);
A more involved example can be found in the README on github.
Check out this url : https://temboo.com/library/Library/Fitbit/OAuth/ and https://temboo.com/library/Library/Fitbit/OAuth/InitializeOAuth/
In order to run java code to generate OAuth url, you will need temboo.jar file which you can download by clicking on java icon on right hand side link.
cheers.

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.

Categories

Resources