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.
Related
How do I implement oauth 2.0 in Android? I was able to obtain a token but
https://api.linkedin.com/v1/people/~:(email-address,first-name,last-name)?oauth2_access_token=
was not able to verify it. How do I send my client id as parameter? I used the following code to authenticate.
LISessionManager.getInstance(getApplicationContext()).init(this, buildScope(), new AuthListener() {
#Override
public void onAuthSuccess() {
LISessionManager liSessionManager = LISessionManager.getInstance(getApplicationContext());
handleLinkedIn(liSessionManager);
Log.d( "success", LISessionManager.getInstance(getApplicationContext()).getSession().getAccessToken().toString());
}
#Override
public void onAuthError(LIAuthError error) {
Toast.makeText(getApplicationContext(), "failed " + error.toString(), Toast.LENGTH_LONG).show();
}
}, true);
I used this method to obtain the access token.
LISessionManager.getInstance(getApplicationContext()).getSession().getAccessToken().toString()
That is not the correct access token that you are sending. See this example get access token from linkedIn
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.
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
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!
I am integrating twitter in my android app. I am able to authorize the app for the user. Now, I am looking for the API which gives me logged users information like first name, last name, email, etc.
I had done this for facebook with
facebook.request("me");
Now how to get user info from twitter?
I am using twitter4j-core-android2.2.3.jar. Plz let me know is there a way to get user info.
Finally I got user information.
use the access token you get after
accessToken = twitterConnection.getOAuthAccessToken
(requestToken,editPinCode.getText().toString());
oHelper.storeAccessToken(accessToken);
Log.i("Access Token:", accessToken.getToken());
Log.i("Access Secret:", accessToken.getTokenSecret());
long userID = accessToken.getUserId();
User user = twitterConnection.showUser(userID);
user.getName();
Thanks.
There are a few tutorials here that can help you get an app running with twitter..
if you just need to retrieve info for a specific user, you can look here (includes source code):
Basic Adroid Twitter Integration
If you want to interact with twitter (e.g. post updates etc) then you will need to setup OAuth connection:
Android and Twitter integratin using OAuth
Twitter.getApiClient(session).getAccountService().verifyCredentials(true, false).enqueue(new Callback<User>()
{
#Override
public void success(Result<User> userResult)
{
try
{
User user = userResult.data;
// twitterImage = user.profileImageUrl;
} catch (Exception e)
{
e.printStackTrace();
}
}
#Override
public void failure(TwitterException e)
{
}
});
You cannot get Email from the twitter OAuth unless or untill your app is whitelisted.
For more Info
Email ID from Twitter
You can check bellow code: To get user info you can use Twitter Fabric SDK. Its documentation is here and here
twitterButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
// Do something with result, which provides a TwitterSession for making API calls
AccountService ac = Twitter.getApiClient(result.data).getAccountService();
ac.verifyCredentials(true, true, new Callback<com.twitter.sdk.android.core.models.User>() {
#Override
public void success(Result<com.twitter.sdk.android.core.models.User> result) {
String imageUrl = result.data.profileImageUrl;
String email = result.data.email;
String userName = result.data.name;
System.out.println(imageUrl);
System.out.println(email);
System.out.println(userName);
}
#Override
public void failure(TwitterException e) {
Log.d("ls",e.getMessage());
}
});
}
#Override
public void failure(TwitterException exception) {
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.app_name),
Toast.LENGTH_SHORT).show();
}
});
Here twitterButton is
import com.twitter.sdk.android.core.identity.TwitterLoginButton;
In this response you can get All credential without user Email.