How to authenticate user in Uber SDK in Android? - android

With reference to this link, I integrated the Uber sdk into my app.before that I registered my application in the Uber developer site got my client id and the client secret.
I added the below code in my application class:
UberSdk.initialize(this, "MY_CLIENT_ID");
UberSdk.setRedirectUri("MY_REDIRECT_URI");
UberSdk.setSandboxMode(true);
Then in my fragment:
oncreate():
accessTokenManager = new AccessTokenManager(getContext());
loginManager = new LoginManager(accessTokenManager);
List<Scope> scopes = new ArrayList<Scope>();
scopes.add(Scope.PROFILE);
scopes.add(Scope.RIDE_WIDGETS);
Date expirationTime = new Date(System.currentTimeMillis());
String token = "Token";
AccessToken accessToken = new AccessToken(expirationTime, scopes, token);
accessTokenManager.setAccessToken(accessToken);
Log.d("ttt", "accessToken: " + accessTokenManager.getAccessToken());
loginManager.loginWithScopes(getActivity(), scopes);
onActivityResult():
LoginCallback loginCallback = new LoginCallback() {
#Override
public void onLoginCancel() {
// User canceled login
Log.d("ttt", " User canceled login " );
Toast.makeText(getContext(), "User canceled login", Toast.LENGTH_SHORT).show();
}
#Override
public void onLoginError(#NonNull AuthenticationError error) {
// Error occurred during login
Log.d("ttt", "Error occurred during login" );
Toast.makeText(getContext(),"Error occurred during login",Toast.LENGTH_SHORT).show();
}
#Override
public void onLoginSuccess(#NonNull AccessToken accessToken) {
// Successful login! The AccessToken will have already been saved.
Log.d("ttt", "Successful login! " );
Toast.makeText(getContext(),"Successful login!",Toast.LENGTH_SHORT).show();
}
};
loginManager.onActivityResult(requestCode, resultCode, data, loginCallback);
I have no idea how to add redirect uri and from where I will get the redirect uri. And what is the actual use of it (searched a lot still not clear with what it does).
Once I click the Uber ride button it navigates to some loginactivity and a popup shows up saying "There was a problem authenticating you".
What I am doing wrong here?

Here's a great write up of what a Redirect URI is used for in Oauth 2.0. What's a redirect URI? how does it apply to iOS app for OAuth2.0?.
TLDR: Your application may exist on the web and for mobile app, and the redirect URI is the endpoint that is redirected back to after the flow is completed. For mobile clients, you could easily set your redirect URI to "http://localhost" in the Uber developer dashboard, since it doesn't have the same requirements as on the web.
We're investigating simplifying this further, so keep an eye out on our future releases!

Related

aws cognito with facebook login? - android

so im really confused on how the facebook login works with aws cognito in android. I was able to hook aws cognito up and the facebook log in just fine. The aws cognito guide gives me these lines of code:
Map<String, String> logins = new HashMap<String, String>();
logins.put("graph.facebook.com", AccessToken.getCurrentAccessToken().getToken());
credentialsProvider.setLogins(logins);
couple questions:
1.Where do i put these lines of code?
2.How do i set up cognito user equal to the login facebook user?
3.And basically, whats a working example of this?
Hope you guys can help!
This is the following code where I have used the facebook login with federated identities from the congnito. first you need to set up the CognitoSyncManagerFile with the appropriate login credentials with the pool details . And then the following code as follows .
//initialize the facebook SDK
FacebookSdk.sdkInitialize(getApplicationContext());
//If access token is already here, set fb session
final AccessToken fbAccessToken = AccessToken.getCurrentAccessToken();
if (fbAccessToken != null) {
setFacebookSession(fbAccessToken);
// btnLoginFacebook.setVisibility(View.GONE);
}
btnLoginFacebook = (Button) findViewById(R.id.btnLoginFacebook);
btnLoginFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// start Facebook Login
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile"));
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
btnLoginFacebook.setVisibility(View.GONE);
new GetFbName(loginResult).execute();
setFacebookSession(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Toast.makeText(MainActivity.this, "Facebook login cancelled",
Toast.LENGTH_LONG).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(MainActivity.this, "Error in Facebook login " +
error.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
});
//Set the session with the following method
private void setFacebookSession(AccessToken accessToken) {
Log.i(TAG, "facebook token: " + accessToken.getToken());
CognitoSyncClientManager.addLogins("graph.facebook.com",
accessToken.getToken());
}
For more information follow the below url
https://github.com/awslabs/aws-sdk-android-samples/tree/master/CognitoSyncDemo
Put this in a spot where your credentials provider has already been initialized, where you have just logged in to Facebook for the user in question.
Once you have included this in the logins map, call credentialsProvider.refresh(). This will link the login to the user's identity.
The official AWS samples repo has an android sample that does all this.

Firebase authWithOauthToken is not working

I am developing an app in Android using firebase.I have created the login activity where i have a method that logs user in when they pass the credentials(user creation is already done).Then i will save the token recieved in onAuthenticated callback so that i can log user in automatically next time when he/she opens the app without asking to enter the credentials.
Here is the code
private void loginWithPassword(final String email, String password) {
progressDialog.show();
FirebaseConnections.getConnection().authWithPassword(email, password,
new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
// Authentication just completed successfully :)
IGStorePreference.getInstance().saveString(Constants.TOKEN, authData.getToken());
IGStorePreference.getInstance().saveString(Constants.UID, authData.getUid());
IGStorePreference.getInstance().saveString(Constants.PROVIDER, authData.getProvider());
dismissProgressDialog();
}
#Override
public void onAuthenticationError(FirebaseError error) {
// Something went wrong :(
dismissProgressDialog();
Snackbar.make(parentView, error.getMessage(), Snackbar.LENGTH_LONG).show();
}
});
}
And then i check onCreate whether we have token token to log user in
private void checkIfTokenExistAndLogin() {
if (IGStorePreference.getInstance().isPrefExists(Constants.TOKEN)) {
progressDialog.show();
String provider = IGStorePreference.getInstance().getString(Constants.PROVIDER);
String token = IGStorePreference.getInstance().getString(Constants.TOKEN);
FirebaseConnections.getConnection().authWithOAuthToken(provider, token, new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
IGStorePreference.getInstance().saveString(Constants.TOKEN, authData.getToken());
IGStorePreference.getInstance().saveString(Constants.UID, authData.getUid());
IGStorePreference.getInstance().saveString(Constants.PROVIDER, authData.getProvider());
dismissProgressDialog();
}
#Override
public void onAuthenticationError(FirebaseError firebaseError) {
dismissProgressDialog();
Snackbar.make(parentView, firebaseError.getMessage(), Snackbar.LENGTH_LONG).show();
}
});
}
}
But the problem is that i am getting an error while login user with authWithOAuthToken.Please help what i am missing.
This is the error i recieve everytime.
FirebaseError: Invalid authentication credentials provided.
authWithOAuthToken is used to login with a social provider. For example, user signs in with Google and gets an OAuth token returned from Google. Then app sends this OAuth token to Firebase auth server via authWithOAuthToken. User can log in after server verifies the OAuth token.
In your case, user logged in with email/password. The token you received was a Firebase auth token issued by Firebase auth server not an OAuth token issued by social provider.
Please refer to the doc for details: https://firebase.google.com/support/guides/firebase-android#sign_a_user_in_with_a_social_provider_numbered

Disabling graph api calls without app secret

I am developing an android app for sharing images. I wish to integrate Facebook SDK in the app.
I am getting user access token from the app. Then this token will be used from the server to download and store images in our server. I want to make our user's information safe. I don't want someone else to get user information if they somehow get access to the token from my app.
I have enabled Require App Secret in Facebook app dashboard, but when i call the graph api with this access token from my computer, it is giving me a valid response (i.e. I am able to extract user information with the token outside the app without using app_secret). However, when I get access to the token of Test users from the developer dashboard and try making calls to the graph API, I am getting:
"error": {
"message": "The access token could not be decrypted",
"type": "OAuthException",
"code": 190
}
Which is exactly what I wanted. So I am doing something wrong when I collect the user's token. Below is my logging in code:
loginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday, user_photos, user_friends"));
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
private ProfileTracker mProfileTracker;
#Override
public void onSuccess(final LoginResult loginResult) {
mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile1, Profile profile) {
/**
* Getting userId and storing to SP as long
*/
final String userId = loginResult.getAccessToken().getUserId();
/**
* Getting facebook profilePic, Name and token and storing to SP
*/
String profileImgUrl = "https://graph.facebook.com/" + userId + "/picture?type=large";
final String token = loginResult.getAccessToken().getToken();
if (profile == null) return;
String name = profile.getName();
}
};
mProfileTracker.startTracking();
}
#Override
public void onCancel() {
Log.d("facebook - onCancel", "cancelled");
Snackbar.make(findViewById(android.R.id.content), "Login failed! Please try again.",
Snackbar.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException e) {
Log.d("facebook - onError", e.getMessage());
Snackbar.make(findViewById(android.R.id.content), "Login failed! Please try again.",
Snackbar.LENGTH_SHORT).show();
}
});
Can anyone help me in finding the problem? Thanks in advance.

How to link Google + signed in users on Parse backend on Android?

I've been using Parse for 3 months in my android app. Now I want to add email login and social sign ons (Facebook and Google+) in the app. I have successfully added email and fb login and the user can connect both or either one of email or facebook and the app would recognise the user.
e.g. If I login through email, then connect facebook, use the app on another device, login via facebook, the app would know it's the same user and would be customised for me and would show my data. And email also works.
I have added Google+ sign-in for Android but I am not able to connect the user's Google+ credentials with the logged in user.
Parse Users table has an authData field which gets the facebook auth data and would get Twitter as well as both of these sign ons are baked into Parse SDKs.
What should be the best thing to do for Google+? I'm confused about the db design as well as how to connect the user who signed in with Google+?
What if the user just logs in via Google+? How do I make a Parse User and authenticate the user on Parse?
I'm comfortable with cloud code and Android and would really appreciate some sort of help/instructions just pushing me in the correct direction. I have never used OAuth2 and with Parse login for email and Social Sign ons, I don't think I should get into it. But let me know if I'm wrong.
Thanks!
Update: I have read a lot of questions on Parse Questions and have checked out the become method plenty of times (because I kept thinking I'm missing something after reading that). Check this question - I'm currently in the same situation.
I have:
1. Implemented Google+ sign in.
2. Got access token using GoogltAuthUtil.
Stuck with:
3. How to link currently signed in Parse user after the user signs in with Google+?
4. How to create a new Parse User if Google+ was the user's first (and only ) login choice?
This seems to be similar with
How to create a parse _User account from a Android Google token?
Following is my answer in that thread:
1. New User
The flow is as below:
User authorizes and a token is acquired
We create a new user with a random password
You can create a ParseUser using following code inside the newChooseAccountIntent() method that return email.
ParseUser user = new ParseUser();
user.setUsername(mEmail);
user.setPassword(randomPassword);
user.setEmail(mEmail);
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
// Hooray! Let them use the app now.
} else {
// Sign up didn't succeed. Look at the ParseException
// to figure out what went wrong
}
}
});
2. Returning User
This is the where most of people stuck, as I researched over the Internet. The flow is as below:
User authorizes and the app gets a token
We pass this token to Cloud Code to validate. We need to check if this token is signed by Google and if it is meant for us (android-developers (2013)).
After you can verify that the token is valid, you can query for the user in Cloud Code using Parse.Cloud.useMasterKey() method and return the session key by using getSessionToken() method on the query result.
Use the session key to save login state on disk by calling becomeInBackground method
To validate the token, you can send Parse.Cloud.httprequest to this endpoint: https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=. This is instructed in Google Identity Documentation. You will receive data as below:
{
"iss": "https://accounts.google.com",
"sub": "110169484474386276334",
"azp": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
"email": "billd1600#gmail.com",
"at_hash": "X_B3Z3Fi4udZ2mf75RWo3w",
"email_verified": "true",
"aud": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
"iat": "1433978353",
"exp": "1433981953"
}
Things need to compare are "aud", "azp" and "email" which are translated as audience, authorized party and email.
To query for the current user on Cloud Code:
var query = new Parse.Query(Parse.User);
query.equalTo("email",mEmail);
query.first({
success: function(user) {
// Use user..getSessionToken() to get a session token
},
error: function(user, error) {
//
},
useMasterKey: true
});
Note: Make sure you have following scope so that the email will show up when you check on Cloud Code: https://www.googleapis.com/auth/plus.profile.emails.read
There's a question about this on Parse's questions. It's right here and I'm pretty sure it answers your questions.
https://parse.com/questions/google-plus
It links to the parse blog, that has some workarounds on this.
It says that you can add any login into ParseUser. You would be doing something like this:
Parse.User.become("session-token-here").then(function (user) {
// The current user is now set to user.
}, function (error) {
// The token could not be validated.
});
Another site where you should take a look:
https://parse.com/tutorials/adding-third-party-authentication-to-your-web-app
This last one is official and has an example code
void createNewGPlusUser(final String email, String name) {
final ParseUser user = new ParseUser();
user.setUsername(email);
user.setPassword("my pass");
user.put("any other variable in User class", "value");
user.setEmail(email);
user.put("name", name);
signInParseUser(user, email);
}
void signInParseUser(final ParseUser user, final String email) {
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
Log.d("TAG", "Created user");
// Hooray! Let them use the app now.
login(email);
} else {
Log.d("TAG", "Failed Creating user");
e.printStackTrace();
// Sign up didn't succeed. Look at the ParseException
// to figure out what went wrong
}
}
});
}
void login(final String email) {
ParseUser.logInInBackground(email, "my pass", new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
// Hooray! The user is logged in.
Log.d("TAG", "Login successful");
} else {
// Signup failed. Look at the ParseException to see what happened.
}
}
});
}
To do so, I have used the following code
ParseUser.becomeInBackground(ParseUser.getCurrentUser().getSessionToken(), new LogInCallback() {
#Override
public void done(ParseUser parseUser, ParseException e) {
if (parseUser != null) {
parseUser.setUsername(userEmail);
//firstName and lastName I am getting from Person class of google plus api
parseUser.put("FirstName", firstName);
parseUser.put("LastName", lastName);
parseUser.saveInBackground();
ParseUtils.verifyParseConfiguration(context);
ParseUtils.subscribeWithUsername(strEmail);
Intent successIntent = new Intent(context, OurServicesActivity.class);
startActivity(successIntent);
overridePendingTransition(R.animator.fade_in, R.animator.fade_out);
finish();
} else {
Log.e(TAG, e.getMessage());
Utilities.showToast(context, "Something occurred");
}
}
});
Let me know if it helps or if you have used something else.
Try this
ParseUser.becomeInBackground("session-token-here", new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
// The current user is now set to user.
} else {
// The token could not be validated.
}
}
})

Firebase: How to keep an Android user logged in?

I'm using Firebase SimpleLogin to enable Email / Password authentication. Creation of users and subsequent login is all working fine. However, whenever I leave the app (even if only for a few seconds) the user is never logged in on my return i.e...
authClient.checkAuthStatus(new SimpleLoginAuthenticatedHandler())...
Always returns a null user.
I am not logging out the user via the API. Also I have set the number of days the user is logged in to 21 in the Firebase console.
I have seen mention of a remember-me param in the JS docs, but I can't see any equivalent for Android / Java.
Wondering if I'm missing anything in the docs or if it's not possible for Android?
Thanks for your help,
Neil.
Edit: Added code sample.
User creation....
public void registerUserForChat(final MyApplication application, String email, String password) {
Firebase ref = new Firebase(FIREBASE_URL);
SimpleLogin authClient = new SimpleLogin(ref);
authClient.createUser(email, password, new SimpleLoginAuthenticatedHandler() {
#Override
public void authenticated(com.firebase.simplelogin.enums.Error error, User user) {
if(error != null) {
Log.e(TAG, "Error attempting to create new Firebase User: " + error);
}
else {
Log.d(TAG, "User successfully registered for Firebase");
application.setLoggedIntoChat(true);
}
}
});
}
User login....
public void loginUserForChat(final MyApplication application, String email, String password) {
Log.d(TAG, "Attempting to login Firebase user...");
Firebase ref = new Firebase(FirebaseService.FIREBASE_URL);
final SimpleLogin authClient = new SimpleLogin(ref);
authClient.checkAuthStatus(new SimpleLoginAuthenticatedHandler() {
#Override
public void authenticated(com.firebase.simplelogin.enums.Error error, User user) {
if (error != null) {
Log.d(TAG, "error performing check: " + error);
} else if (user == null) {
Log.d(TAG, "no user logged in. Will login...");
authClient.loginWithEmail(email, password, new SimpleLoginAuthenticatedHandler() {
#Override
public void authenticated(com.firebase.simplelogin.enums.Error error, User user) {
if(error != null) {
if(com.firebase.simplelogin.enums.Error.UserDoesNotExist == error) {
Log.e(TAG, "UserDoesNotExist!");
} else {
Log.e(TAG, "Error attempting to login Firebase User: " + error);
}
}
else {
Log.d(TAG, "User successfully logged into Firebase");
application.setLoggedIntoChat(true);
}
}
});
} else {
Log.d(TAG, "user is logged in");
}
}
});
}
So loginUserForChat method first checks to see if there is a logged in user and, if not, performs the login. Note that every time I start the app, the logging I see is....
Attempting to login Firebase user...
no user logged in. Will login...
User successfully logged into Firebase
If I exit the app, even for a few seconds, and return - I see the same logging.
One thing I noticed is that the call to checkAuthStatus does not take any user credentials - I assume it just checks for any locally logged in user?
Much appreciated.
Another way - try this code in your onCreate:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// User is signed in
Intent i = new Intent(LoginActivity.this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
This will keep the user logged in by taking the user to the Main activity directly without stopping at registration activity. so the user will be logged in unless the user click on signout.
[Engineer at Firebase] In order to transparently handle persistent sessions in the Firebase Simple Login Java client, you need to use the two-argument constructor which accepts an Android context, i.e. SimpleLogin(com.firebase.client.Firebase ref, android.content.Context context) every time you instantiate the Simple Login Java client.
See https://www.firebase.com/docs/java-simple-login-api/javadoc/com/firebase/simplelogin/SimpleLogin.html for the full API reference.
The proper way to do it is to use oAuth authentication:
1. The user logs in.
2. You generate an access token(oAuth2).
3. Android app saves the token locally.
4. Each time the comes back to the auth, he can use the token to to log in, unless the token has been revoked by you, or he changed his
password.
Luckily, firebase has an out of the box support for that, docs:
https://www.firebase.com/docs/security/custom-login.html
https://www.firebase.com/docs/security/authentication.html
You can do this by Using this Approach to escape logi page if User already logged in.
private FirebaseAuth auth;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
startActivity(new Intent(Login_Activity.this, Home.class));
finish();
}
setContentView(R.layout.activity_login_);
for those using Kotlin, to keep the user logged in just add in the onCreate function
if (auth.currentUser != null)
{
startActivity(Intent(this#Login, SellingPageHolderActivity::class.java))
finish()
}

Categories

Resources