Twitter login provider doesn't return access Token to deal with twitter API and post on user's behalf
See original GitHub issueI successfully signed in:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "NearGoal";
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private List<causes> causesList = new ArrayList<>();
private List<FundItem> fundItemList = new ArrayList<>();
private RecyclerView rv;
private RecyclerView rvgoal;
private causes_adaptor cAdapter;
private causes_adaptor_near_goal gAdapter;
private ProgressBar pb;
private ProgressBar progressBarGral;
private Context mContext;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
// already signed in
} else {
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setProviders(Arrays.asList(
new AuthUI.IdpConfig.Builder(AuthUI.TWITTER_PROVIDER).build()))
.build(),
RC_SIGN_IN);
}
Fresco.initialize(getApplication());
setContentView(R.layout.activity_main);
rv = (RecyclerView) findViewById(R.id.rv);
rvgoal = (RecyclerView) findViewById(R.id.rvgoal);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
rv.setLayoutManager(mLayoutManager);
rv.setItemAnimator(new DefaultItemAnimator());
RecyclerView.LayoutManager gLayoutManager =new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
rvgoal.setLayoutManager(gLayoutManager);
rvgoal.setDrawingCacheEnabled(true);
rvgoal.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
rvgoal.setItemAnimator(new DefaultItemAnimator());
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("Your Title");
//toolbar.setTitleTextColor(getResources().getColor(android.R.color.transparent));
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
//tabLayout = (TabLayout) findViewById(R.id.tabs);
//tabLayout.setupWithViewPager(viewPager);
//collapsingToolbarLayout.setTitle(" ");
pb=(ProgressBar) findViewById(R.id.ProgressBar);
progressBarGral = (ProgressBar) findViewById(R.id.progress_bar);
// String url = "http://10.0.2.2:3000/api/campaigns/get/all//api/campaigns/get/all/";
new DownloadTask().execute();;
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
}
};
}
public class DownloadTask extends AsyncTask<String, Void, Integer> {
URL url = null;
@Override
protected void onPreExecute() {
progressBarGral.setVisibility(View.VISIBLE);
}
@Override
protected Integer doInBackground(String... params) {
Integer result = 0;
HttpURLConnection urlConnection;
try {
url = new URL(getResources().getString(R.string.backend_base_url)+"/api/campaigns/get/all/");
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
// 200 represents HTTP OK
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
parseResult(response.toString());
result = 1; // Successful
} else {
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
@Override
protected void onPostExecute(Integer result) {
progressBarGral.setVisibility(View.GONE);
if (result == 1) {
gAdapter = new causes_adaptor_near_goal(MainActivity.this, causesList);
//gAdapter = new causes_adaptor_near_goal(getApplicationContext(), causesList);
rvgoal.setAdapter(gAdapter);
cAdapter = new causes_adaptor(MainActivity.this, causesList);
//gAdapter = new causes_adaptor_near_goal(getApplicationContext(), causesList);
rv.setAdapter(cAdapter);
} else {
Toast.makeText(MainActivity.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show();
}
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.getJSONArray("rows");
causesList = new ArrayList<>();
JSONArray funds;
for (int i = 0; i < posts.length(); i++) {
fundItemList = new ArrayList<>();
JSONObject post = posts.optJSONObject(i);
funds = post.getJSONArray("foundations");
causes item = new causes();
item.setName(post.optString("name"));
item.setcause_description(post.optString("cause_description"));
item.setGoal(post.optString("goal"));
item.setCurrent_contributions(post.optString("current_contributions"));
item.setTotalUniqueUsersReached(post.optString("totalUniqueUsersReached"));
item.setState(post.optString("state"));
item.setId(post.optString("_id"));
item.setRemaining_ammount_to_goal(post.optString("remaining_ammount_to_goal"));
item.setGoal_percentage_achieved(post.optString("goal_percentage_achieved"));
item.setCampaign_ending_date(post.optString("campaign_ending_date"));
for(int k=0, len=funds.length(); k <len;k++) {
FundItem fundItem = new FundItem();
JSONObject fund = funds.optJSONObject(k);
fundItem.setTwitter_account(fund.getString("twitter_account"));
fundItem.setName(fund.getString("name"));
fundItem.setPic_path(fund.getString("pic_path"));
fundItemList.add(fundItem);
}
item.setFundlist(fundItemList);
causesList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_home, menu);
return true;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
// user is signed in!
Log.d("user_status","user signed in!!");
return;
}
// Sign in canceled
if (resultCode == RESULT_CANCELED) {
/* startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setProviders(Arrays.asList(
new AuthUI.IdpConfig.Builder(AuthUI.TWITTER_PROVIDER).build()))
.build(),
RC_SIGN_IN);*/
return;
}
// User is not signed in. Maybe just wait for the user to press
// "sign in" again, or show a message.
}
/*private void handleTwitterSession(TwitterSession session) {
Log.d(TAG, "handleTwitterSession:" + session);
AuthCredential credential = TwitterAuthProvider.getCredential(
session.getAuthToken().token,
session.getAuthToken().secret);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(getApplicationContext(), "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}*/
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
But I'm not beign able to get the access token to interact with the Twitter API on user's behalf. I already checked all the provider properties and the mAuth object but I can't seem to find the token. How can I retrieve that after the successful login? The docsdoesn'tseem to sayanything about that token
Issue Analytics
- State:
- Created 7 years ago
- Comments:5 (1 by maintainers)
Top Results From Across the Web
OAuth 1.0a: how to obtain a user's Access Tokens | Docs
First, check that 3-legged OAuth is enabled under your App's authentication settings. You can manage these settings from within the Twitter developer portal....
Read more >OAuth 2.0 Making requests on behalf of users | Docs
You can create a refresh token by making a POST request to the following endpoint: https://api.twitter.com/2/oauth2/token You will need to add in the...
Read more >Overview of the different authentication methods | Docs
This authentication method allows you to send your developer App's Consumer Keys (API Key and Secret), alongside a set of user access Tokens...
Read more >Twitter API Response Codes & Error Support
Different error codes indicate different reasons for an error. The Twitter API attempts to return appropriate HTTP status codes for every request.
Read more >Log in with Twitter | Docs | Twitter Developer Platform
To start a sign-in flow, your Twitter app must obtain a request token by sending a signed message to POST oauth/request_token. The only...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
You’re welcome, these questions should probably be for stack overflow and Google… However, as my last bit of advice, check out the twitter documentation (you don’t need to add the dependency because firebase ui already has it, but you probably should to ensure you always get the latest version). The rest is pretty clear to compose a tweet. Hope this helps!
BTW, you don’t need your users to log into twitter for what you’re trying to do. The consumer key and secret are found here: https://apps.twitter.com/ which is all you really need. Firebase-UI is meant to let users authenticate with Firebase services such as the database and storage. It also gives you a unique uid to let you identify your users.
@SUPERCILEX thanks for chiming in, @juanlet I am going to close this issue as what’s left has more to do with the Twitter API than FirebaseUI. Hope you get it all working.