I’m building an Android app that needs to connect to Google Drive documents. I keep getting a “401 Cannot parse AuthSub token” error when trying to authenticate.
I think the issue is that Android’s AccountManager is returning the wrong type of access token. Is there a proper way to get a valid access token using AccountManager for Google Drive access, or should I use a different authentication method?
Here’s my current implementation:
import com.google.api.client.googleapis.extensions.android.accounts.GoogleAccountManager;
import com.google.api.services.drive.DriveClient;
import com.google.api.services.drive.DriveUrl;
import com.google.api.services.drive.model.FileEntry;
import com.google.api.services.drive.model.FileFeed;
public class MainActivity extends ListActivity{
private static final String TOKEN_SCOPE = "https://www.googleapis.com/auth/drive";
private static final HttpTransport TRANSPORT = new NetHttpTransport();
protected DriveClient driveClient;
String userAccount;
GoogleAccountManager manager;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
driveClient = new DriveClient(TRANSPORT.createRequestFactory(authCredential));
manager = new GoogleAccountManager(this);
handleAccount();
}
void handleAccount() {
manager.getAccountManager().getAuthToken(selectedAccount, TOKEN_SCOPE, true, new AccountManagerCallback<Bundle>() {
public void run(AccountManagerFuture<Bundle> result) {
try {
Bundle data = result.getResult();
if (data.containsKey(AccountManager.KEY_INTENT)) {
Intent authIntent = data.getParcelable(AccountManager.KEY_INTENT);
authIntent.setFlags(authIntent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(authIntent, AUTH_REQUEST_CODE);
} else if (data.containsKey(AccountManager.KEY_AUTHTOKEN)) {
updateAuthToken(data.getString(AccountManager.KEY_AUTHTOKEN));
processToken();
}
} catch (Exception ex) {
Log.e(LOG_TAG, ex.getMessage(), ex);
}
}
}, null);
}
void updateAuthToken(String token) {
authCredential.setAccessToken(token);
}
void processToken() {
List<String> fileList = new ArrayList<String>();
FileFeed documents = driveClient.executeGetFileFeed(DriveUrl.forDefaultPrivateFiles());
for (FileEntry file : documents.files) {
fileList.add(file.name);
}
//Process the file list
}
}