Android switch from Parse to Parse Server crashes - android

I'm migrating my Android and iOS app from Parse.com to Parse Server. First I'm doing this migration with a test app to be sure everything is ok.
With iOS there has been no problem but with Android the updated app crashes each time the user enters in the app.
This is the Android code updated:
public static void initParse(Application app) {
ctxt = app.getApplicationContext();
Parse.enableLocalDatastore(app);
// Old version
//Parse.initialize(app, "<my app id>", "<my client key>");
// New version
Parse.initialize(new Parse.Configuration.Builder(ctxt)
.applicationId("<my app id>")
.clientKey(null)
.server("https://<my new server>/parse/")
.build()
);
ParseUser.enableRevocableSessionInBackground();
}
The crash returns a "com.parse.ParseException: java.lang.IllegalStateException: unable to encode an association with an unsaved ParseObject", and taking into account what I've read in Stackoverflow, this is because ParseUser.getCurrentUser() returns null (despite the user is logged in) and Parse methods fail.
In fact, if I take this same code, uncomment the old version of Parse.initialize, comment the new version of Parse.initialize, compile and launch the app, this is launched without problems and the user can use it properly.
But again, if I comment the old version of Parse.initialize, uncomment the new version of Parse.initialize, compile and launch the app, this crashes inmediately because ParseUser.getCurrentUser() returns null and Parse methods fail.
What am I missing here? Should I force my users to login again? This seems to me a bad UX, and anyway, in iOS I have no problems with the new version, what is the difference between both platforms?
EDIT 1:
Following Robert Rowntree advice I've changed the initialization to this:
public static void initParse(Application app) {
ctxt = app.getApplicationContext();
Parse.enableLocalDatastore(app);
// Old version
//Parse.initialize(app, "<my app id>", "<my client key>");
// New version
Parse.initialize(new Parse.Configuration.Builder(ctxt)
.applicationId("<my app id>")
.clientKey("<my client key>")
.server("https://<my new server>/parse/")
.build()
);
//Parse.setLogLevel(Parse.LOG_LEVEL_DEBUG);
Parse.setLogLevel(Parse.LOG_LEVEL_VERBOSE);
ParseUser.enableRevocableSessionInBackground();
}
Besides this I've checked that my Parse version is the last available, I have this in my gradle file:
compile 'com.parse.bolts:bolts-android:1.+'
compile 'com.parse:parse-android:1.+'
And the result is the same, the app crashes with "com.parse.ParseException: java.lang.IllegalStateException: unable to encode an association with an unsaved ParseObject" the first call I make to Parse.
Besides this, the unique log I can see related to parse is one related to GCM token, nothing else.
EDIT 2:
I've tried another thing, uninstall the app with the old initialization and install it with the new initialization and as I guessed the new version is now working.
But, of course this is not a solution to me, I can not tell my users to uninstall the app ans install it again.
But this is a hint: there is no problem with the new initialization but with how the old Parse "reacts" when opening the app with the new Parse Server, there must be any inconsistency in getCurrentUser or something like that.

Can you try initializing like this:
Parse.initialize(new Parse.Configuration.Builder(this)
.applicationId("APP_ID")
.clientKey("CLIENT_KEY")
.server("https://SERVER_URL/parse/") // The trailing slash is important.
.enableLocalDataStore()
.build()
);
notice the
.enableLocalDataStore()
is in the initilization. Remove this:
Parse.enableLocalDatastore(app);

Related

Spotify Authentication auth_service_unavailable

I am trying to login to spotify.
Although when the app is installed it always throws an AUTHENTICATION_SERVICE_UNAVAILABLE error. If the app is uninstalled the default Webview opens where the login works fine. Wished behaviour is, that the app opens and the user can login from there.
public void doSpotifyLogin(boolean trySpotifyAgain) {
this.trySpotifyAgain = trySpotifyAgain;
AuthorizationRequest.Builder builder =
new AuthorizationRequest.Builder(CLIENT_ID, AuthorizationResponse.Type.TOKEN, REDIRECT_URI);
builder.setScopes(new String[]{"user-read-private", "streaming", "playlist-read-private", "user-library-read"});
AuthorizationRequest request = builder.build();
AuthorizationClient.openLoginActivity(this, SPOTIFY_LOGIN_REQUEST_CODE, request);
}
This is the response I am getting from the API:
2021-12-22 11:36:29.802 5069-5069/? I/com.spotify.sdk.android.auth.LoginActivity: Spotify auth completing. The response is in EXTRA with key 'response'
2021-12-22 11:36:29.822 5069-5069/? D/StartActivity: Spotify error: AUTHENTICATION_SERVICE_UNAVAILABLE
If you need any further information, please let me know! Thanks in advance
Ronze's comment worked for me. I needed to update my app's package name on developer.spotify.com.
For me, the issue got resolved after I added the SHA1 key generated on a new mac to the Spotify app dashboard

Branch.io deferred deep link missing data after install

I'm trying to get deferred deep links working on Android. I added a test device in the dashboard & reset the device data and made sure the app is uninstalled. When I click a branch.io link, it takes me to the play store as expected. I then launch the app from Android Studio onto the phone, then the logs say that Branch SDK sent a request to https://api2.branch.io/v1/install, but the problem is the response doesn't contain the original link, query params, or key value pairs I set in the dashboard. This is the JSONObject I'm receiving in onInitFinished:
{"+match_guaranteed":true,"link_click_id":"976953359423305632","+clicked_branch_link":true,"+click_timestamp":1634196720,"+is_first_session":true,"utm_source":"test-referrer"}
Where is all the other information? This doesn't include the original link, the key-value pairs, tags, etc.
For a comparison, this is what I receive in the iOS app:
["$ios_passive_deepview": "branch_passive_default", "source": "test-referrer", "+is_first_session": 1, "~channel": test-referrer, "$matching_ttl_s": 7200, "~id": 976763609660742721, "~creation_source": 1, "$one_time_use": 0, "~marketing": 1, "~referring_link": "https://myapp.test-app.link/test-referrer", "~feature": "test", "+click_timestamp": 1634249299, "+match_guaranteed": 0, "$og_description": "My app description", "$og_title": "MyApp", "+clicked_branch_link": 1, "$marketing_title": "Test Referral Link", "~tags": ["test-referrer"], "~campaign": "test"]
If I rotate the phone to recreate the Activity or reopen the app a single time, it then sends a request to https://api2.branch.io/v1/open and returns all the info I expected initially. How do I get the information after installing the app?
I'm currently testing with myapp.test-app.link, and I call Branch.enableTestMode() before Branch.getAutoInstance(this) in my custom Application class's onCreate(). I also tried with a live link and got the same result.
These are the libraries I'm using in build.grade:
implementation 'io.branch.sdk.android:library:5.0.13'
implementation 'com.google.firebase:firebase-appindexing:20.0.0'
implementation 'com.google.android.gms:play-services-ads-identifier:17.1.0'
implementation 'androidx.browser:browser:1.3.0'
I've also set up app links and the uri scheme in the dashboard as well as in the app. Using getFirstReferringParams() and getLatestReferringParams() on the first session after installing doesn't help either.
UPDATE:
Repeating the exact same testing process I described above, now the JSONObject that gets passed into onInitFinished has even less information and is claiming that I'm not clicking a branch link:
{"+clicked_branch_link":false,"+is_first_session":true}
And getFirstReferringParams() returns an empty json object.
I'm about to start looking for an alternative at this rate.
I fixed this issue by adding intent.putExtra("branch_force_new_session", true); right after this.activity.setIntent(intent); when initialising the intent. Something like this:
...
this.activity.setIntent(intent);
intent.putExtra("branch_force_new_session", true);
Branch
.sessionBuilder(this.activity)
.withCallback(branchReferralInitListener)
.reInit();
...
Look here for the branch_force_new_session reference.
The other reason for the missing data is the non-existent link alias, but it looks like it is not the case as soon as you tried with the same link in iOS.

Deleting a user from Azure Active Directory B2C Android/Java

I have an Android application in which I'm using Azure AD B2C to authenticate users. Users login and logout of the application as needed. I would like to give the user the option to delete their own account.
I understand that I need to use the Azure AD Graph API to delete the user. This is what I have so far:
According to this link, it looks like deleting a user from a personal account (which is what the B2C users are using) is not possible. Is that correct?
Here's my code snippet for the Graph API call. Feel free to ignore it if I'm off track and there is a better way to solve this.
I believe I need a separate access token than what my app currently has (as the graph API requires other API consent). So, I'm getting the access token as follows:
AcquireTokenParameters parameters = new AcquireTokenParameters.Builder()
.startAuthorizationFromActivity(getActivity())
.fromAuthority(B2CConfiguration.getAuthorityFromPolicyName(B2CConfiguration.Policies.get("SignUpSignIn")))
.withScopes(B2CConfiguration.getGraphAPIScopes())
.withPrompt(Prompt.CONSENT)
.withCallback(getGraphAPIAuthCallback())
.build();
taxApp.acquireToken(parameters);
In the getGraphAPIAuthCallback() method, I'm calling the Graph API using a separate thread (in the background):
boolean resp = new DeleteUser().execute(authenticationResult.getAccessToken()).get();
Finally, in my DeleterUser() AsyncTask, I'm doing the following:
#Override
protected Boolean doInBackground(String... aToken) {
final String asToken = aToken[0];
//this method will be running on background thread so don't update UI from here
//do your long running http tasks here,you dont want to pass argument and u can access the parent class' variable url over here
IAuthenticationProvider mAuthenticationProvider = new IAuthenticationProvider() {
#Override
public void authenticateRequest(final IHttpRequest request) {
request.addHeader("Authorization",
"Bearer " + asToken);
}
};
final IClientConfig mClientConfig = DefaultClientConfig
.createWithAuthenticationProvider(mAuthenticationProvider);
final IGraphServiceClient graphClient = new GraphServiceClient.Builder()
.fromConfig(mClientConfig)
.buildClient();
try {
graphClient.getMe().buildRequest().delete();
} catch (Exception e) {
Log.d(AccountSettingFragment.class.toString(), "Error deleting user. Error Details: " + e.getStackTrace());
}
return true;
}
Currently, my app fails when trying to get an access token with a null pointer exception:
com.microsoft.identity.client.exception.MsalClientException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference
Any idea what I need to do to provide the user the option to users to delete their own account? Thank you!
Thanks for the help, #allen-wu. Due to his help, this azure feedback request and this azure doc, I was able to figure out how to get and delete users silently (without needing intervention).
As #allen-wu stated, you cannot have a user delete itself. So, I decided to have the mobile app call my server-side NodeJS API when the user clicks the 'Delete Account' button (as I do not want to store the client secret in the android app) and have the NodeJS API call the Azure AD endpoint to delete the user silently. The one caveat is that admin consent is needed the first time you try to auth. Also, I have only tested this for Graph API. I'm not a 100% sure if it works for other APIs as well.
Here are the steps:
Create your application in your AAD B2C tenant. Create a client secret and give it the following API permissions: Directory.ReadWrite.All ;
AuditLog.Read.All (I'm not a 100% sure if we need the AuditLog permission. I haven't tested without it yet).
In a browser, paste the following link:
GET https://login.microsoftonline.com/{tenant}/adminconsent?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&state=12345
&redirect_uri=http://localhost/myapp/permissions
Login using an existing admin account and provide the consent to the app.
Once you've given admin consent, you do not have to repeat steps 1-3 again. Next, make the following call to get an access token:
POST https://login.microsoftonline.com/{B2c_tenant_name}.onmicrosoft.com/oauth2/v2.0/token
In the body, include your client_id, client_secret, grant_type (the value for which should be client_credentials) and scope (value should be 'https://graph.microsoft.com/.default')
Finally, you can call the Graph API to manage your users, including deleting them:
DELETE https://graph.microsoft.com/v1.0/users/{upn}
Don't forget to include the access token in the header. I noticed that in Postman, the graph api had a bug and returned an error if I include the word 'Bearer' at the start of the Authorization header. Try without it and it works. I haven't tried it in my NodeJS API yet, so, can't comment on it so far.
#allen-wu also suggested using the ROPC flow, which I have not tried yet, so, cannot compare the two approaches.
I hope this helps!
There is a line of code: graphClient.getUsers("").buildRequest().delete();
It seems that you didn't put the user object id in it.
However, we can ignore this problem because Microsoft Graph doesn't allow a user to delete itself.
Here is the error when I try to do it.
{
"error": {
"code": "Request_BadRequest",
"message": "The principal performing this request cannot delete itself.",
"innerError": {
"request-id": "8f44118f-0e49-431f-a0a0-80bdd954a7f0",
"date": "2020-06-04T06:41:14"
}
}
}

How to set android backend minSdk

im working on an android app with some server-side business logic. Im using android studio and im creating that kind of app for a first time.
I am trying to use server-side application to login to a different system and return me a cookie, so my android application can tell, whether the set credentials are correct.
Here's my endpoint provided method.
/** Returns user with cookie set either to null or actual cookie from AIS */
#ApiMethod(name = "login")
public User login(#Named("loginName") String name, #Named("password") String password) {
AISCommunicator aisCommunicator = new AISCommunicator();
String cookieVal = aisCommunicator.login(password,name);
User user = new User();
user.setCookie(cookieVal);
//user.setCookie("asdasdasd");
return user;
}
AISCommunicator is a serverside bean. At the moment it's part of a code
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
is marked as incorrect by Android studio, which tells me, that to use it, i need to declare minSdk level 9, while currently i have 1. How can i do that? I have set minSdk in my client's app, but it seems like it does not influence the serverside bean.
Anyway, the code is still runnable for some reason and the endpoint Bean returns 404 not found error at the moment.
Ignore Android Studio's error. This is one of its known and unfixed bugs.

Empty json data in Release build (using proguard)

My app doesn't post data to server when I run the release version (signed, Proguard packed). But if I run it directly from ADT, I see the data on the server.
It's weird because it just the same code, one is signed and the other is direct execution. Here is the Code (using org.springframework.web.client.RestTemplate):
private static String URL = "https://myappserver.com/abcservice/";
public ResponseEntity<String> sendMessage(UserMessage us) {
private RestTemplate template = getTemplate();
HttpEntity<UserMessage> reqEntity = new HttpEntity<UserMessage>(us, headers);
ResponseEntity<String> result =
template.postForEntity(URL, reqEntity, String.class);
return result;
}
Below are the 2 scenarios:
Case 1: Works Good
Run the App directly from ADT (Run as: Android Application)
User taps a button, which will invoke sendMessage(..) method.
Controller (on Server) gets the request and the data (UserMessage).
An entry with UserMessage is created.
Server send a 201 response (request has been fulfilled), to the app.
Case 2: PROBLEM
Pack the app (Android Tools -> Export Signed Application Package..)
Install it on device through command line (adb install xxx.apk)
Start the app.
User taps a button, which will invoke sendMessage(..) method.
Controller (on Server) gets the request but no data.
An entry with empty UserMessage is created.
Server send a 201 response (request has been fulfilled), to the app.
I have tried to log both on my device and web server, I can confirm that empty data is received for Case 2, and I'm not able to figure out why it doesn't send data when I pack it?
Does packed/released (Signed +Proguard) apps behave differently, compared to debug packaging?
I guess that it is caused by proguard. Proguard is probably obfuscating some portion of your code, but this code is dynamically invoked by Spring (and jackson ? you didn't mention it). (and so once it is obfuscate : dynamic invocation failed)
So try to :
disable proguard to confirm that it is the cause of the problem
if it is confirmed : try to configure it so hat it won't obfuscate class that are serialized in json (i.e. UserMessage) :
-keep class com.company.UserMessage** { *; }
I have same issue, and I committed below 2 line
// shrinkResources true
// minifyEnabled true
The above answer didnt work for me may be it was correct on 2014
For 2019 when I set the compileSdkVersion 28 it works.

Categories

Resources