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
Related
I am integrating LinkedIn Login in my app but it is giving me an error
here is the code of Authentication
private static Scope buildScope() {
return Scope.build(Scope.R_BASICPROFILE, Scope.R_EMAILADDRESS, Scope.W_SHARE);
}
public void signInWithLinkedIn() {
//First check if user is already authenticated or not and session is valid or not
if (!LISessionManager.getInstance(this).getSession().isValid()) {
//if not valid then start authentication
LISessionManager.getInstance(getApplicationContext()).init(this, buildScope()//pass the build scope here
, new AuthListener() {
#Override
public void onAuthSuccess() {
//on successful authentication fetch basic profile data of user
fetchBasicProfileData();
}
#Override
public void onAuthError(LIAuthError error) {
// Handle authentication errors
Log.e(TAG, "Auth Error :" + error.toString());
Toast.makeText(mContext, "Failed to authenticate with LinkedIn. Please try again.", Toast.LENGTH_SHORT).show();
}
}, true);//if TRUE then it will show dialog if
// any device has no LinkedIn app installed to download app else won't show anything
} else {
Toast.makeText(this, "You are already authenticated.", Toast.LENGTH_SHORT).show();
fetchBasicProfileData();
}
}
This is the error:-
Auth Error :{
"errorCode": "UNKNOWN_ERROR",
"errorMessage": "The passed in mobile identifier is invalid \"com.tablefortwo\""
}
public void signInWithLinkedIn(View view){
LISessionManager.getInstance(getApplicationContext()).init(this, buildScope(), new AuthListener() {
#Override
public void onAuthSuccess() {
Toast.makeText(getApplicationContext(), "success" + LISessionManager.getInstance(getApplicationContext()).getSession().getAccessToken().getValue(), Toast.LENGTH_LONG).show();
Log.d("SESSION", Boolean.toString(LISessionManager.getInstance(getApplicationContext()).getSession().isValid()));
//fetchBasicProfileData();
}
#Override
public void onAuthError(LIAuthError error) {
Toast.makeText(getApplicationContext(), "failed " + error.toString(),
Toast.LENGTH_LONG).show();
}
}, true);
// After complete authentication start new HomePage Activity
}
The block of code in onAuthSuccess got executed but getSession returns null AND most importantly the access token is null, making me unable to call other linkedin APIs. This happens only recently. Am I doing it correctly?
Updated:- One more thing it generally happens with few specific LinkedIn Ids and working fine with rest of the id.
LinkedIn is updating its android sdk and they deprecate several methods.They started doing this from this week, I also got the same problem.You should use javascript api's to authenticate user rather than using linkedin android sdk.We fixed ur problem the same way.
I'm trying to create a SyncAdapter for Microsoft calendars and the first step is Authentication. i'm using com.microsoft.aad:adal:2.0.4-alphaand using this code for first authentication:
getAuthenticationContext().acquireToken(
mContextActivity,
Constants.SCOPES.split(" "),
null,
Constants.CLIENT_ID,
Constants.REDIRECT_URI,
PromptBehavior.Auto,
new AuthenticationCallback<AuthenticationResult>() {
#Override
public void onSuccess(final AuthenticationResult authenticationResult) {
if (authenticationResult != null && authenticationResult.getStatus() ==
AuthenticationResult.AuthenticationStatus.Succeeded) {
dependencyResolver = new ADALDependencyResolver(
getAuthenticationContext(),
resourceId,
Constants.CLIENT_ID);
token = authenticationResult.getToken();
UserInfo userInfo = authenticationResult.getUserInfo();
if (userInfo != null) {
userIdentifier = new UserIdentifier(userInfo.getUniqueId(),
UserIdentifier.UserIdentifierType.UniqueId);
}
}
}
#Override
public void onError(Exception t) {
Log.e("initialize", "onError : " + t.getMessage());
result.setException(t);
}
}
);
this works perfectly and after entering username and password i can get token.
BUT this is for sync adapter and at some point i need to get token silently. so i used this code:
public void getTokenSilent() {
getAuthenticationContext()
.acquireTokenSilent(Constants.SCOPES.split(" "),
Constants.CLIENT_ID,
userIdentifier,
new AuthenticationCallback<AuthenticationResult>() {
#Override
public void onSuccess(
AuthenticationResult authenticationResult) {
UserInfo userInfo = authenticationResult.getUserInfo();
}
#Override
public void onError(Exception e) {
Log.e("getTokenSilent", "onError : " + e.getMessage());
}
});
}
After executing this code i got the error:
AUTH_REFRESH_FAILED_PROMPT_NOT_ALLOWED Prompt is not allowed and failed to get token: ver:2.0.4-alpha
onError : Refresh token is failed and prompt is not allowed
how can i resolve this error and get or refresh token silently?
tnx in advance.
If you want to get the token silently, there are two ways for using Azure AD V2.0 endpoint.
First, acquire the access token and refresh token interactively, then get the access token in the cache or renew the access token using refresh token via acquireTokenSilent method.
Second is that the Azure AD V2.0 endpoint also support the Client Credentials flow(refer here) which normally used for the service daemon application. However the MSAL for android doesn't support this flow at present. You need to implement it yourself. You can follow this article about detail of this flow. And this flow only works for the Azure AD account.
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
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.