androidretrofithttp-token-authentication

Retrofit authentication in the next activity


My first activity is the login activity with simplest form and hardcoded credentials for this purpose. POST request is sent to the API and the token is returned as a result. Everything works fine. Now the way I implemented it is I have an intent placed inside the onSuccess method in the onClick event inside the login method. Here's the code:

Login login = new Login("{hardcodedEmail}", "{hardcodedPassword}");
Call<User> call = userClient.login(login);
call.enqueue(new Callback<User>() {
    @Override
    public void onResponse(Call<User> call, Response<User> response) {
        Toast.makeText(MainActivity.this, response.body().getToken(), Toast.LENGTH_LONG).show();
        String token = response.body().getToken();
        Intent i = new Intent(MainActivity.this, TestActivity.class);
        startActivity(i);
   }

   @Override
   public void onFailure(Call<User> call, Throwable t) {
       Toast.makeText(MainActivity.this, "Error: \n" + t.getMessage(), Toast.LENGTH_LONG).show();
   }
});

This code has a simple toast to show me the token and say that everything's ok. It does that, I don't get any errors on this page. But on the next page, I'm trying to retrieve some data from the API and display it, but I'm getting error 401, or unauthorized access. Meaning my credentials didn't stay.

Is there something else I need to do other than just skip right into the next activity to keep the credentials alive?


Solution

  • You can pass token string through Intent from your MainActivity to TestActivity. Feel free to try this:

    call.enqueue(new Callback<User>() {
        @Override
        public void onResponse(Call<User> call, Response<User> response) {
            .....
    
            String token = response.body().getToken();
            Intent i = new Intent(MainActivity.this, TestActivity.class);
    
            // pass token string through Intent
            i.putExtra("TOKEN_STRING", token);
    
            startActivity(i);
       }
    

    Then in TestActivity, get token from Intent pass in:

    // declare token as member variable
    private String token;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        .....
    
        Intent intent = getIntent();
        this.token = intent.getStringExtra("TOKEN_STRING");
    
        // you can do whatever you want with token later
        // eg: use token for authentication when issue next network call
    
        ....
    }