1

I already search all around the places on internet how to add basic auth using retrofit2 but still no luck. I already implemented a simple login mechanism but basic auth must be use in order for successful login.

My model

public class ResObj {

    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

ApiUtils.java

public class ApiUtils {

    public static final String BASE_URL = "xxxxx";

    public static UserService getUserService(){
        return RetrofitClient.getClient(BASE_URL).create(UserService.class);
    }
}

RetrofitClient.java

public class RetrofitClient {

private static Retrofit retrofit = null;

public static Retrofit getClient(String url){
    if(retrofit == null){
        retrofit = new Retrofit.Builder().baseUrl(url).addConverterFactory(GsonConverterFactory.create()).build();
    }

    return retrofit;
}
}

UserService.java

public interface UserService {

    @GET("login?username={username}&password={password}")
    Call<ResObj> login(@Path("username") String username, @Path("password") String password);
}

LoginActivity.java

private void doLogin(String username, String password){
        Call<ResObj> call = userService.login(username, password);
        call.enqueue(new Callback<ResObj>() {
            @Override
            public void onResponse(Call<ResObj> call, Response<ResObj> response) {
                if(response.isSuccessful()){
                    ResObj resObj = response.body();
                    if(resObj.getMessage().equals("true")){
                        Intent intent = new Intent(TextLoginActivity.this, MainActivity.class);
                        startActivity(intent);
                    } else {
                        Toast.makeText(TextLoginActivity.this, "The username and password is incorrect", Toast.LENGTH_SHORT).show();
                    }
                } else{
                    Toast.makeText(TextLoginActivity.this, "Error! Please try again!", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ResObj> call, Throwable t) {
                Toast.makeText(TextLoginActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

    }
halfer
  • 19,824
  • 17
  • 99
  • 186
Nurdin
  • 23,382
  • 43
  • 130
  • 308

1 Answers1

1

As I see your login API request, it exposes the user's password and the username in the query. The least you can do is maybe encrypt it. But a much better solution would be to have a POST request instead of a GET request with the username and password in the body. You add the Authorization header to the API request as follows:

public interface UserService {
    String authorization = "Authorization: Basic XXXXXX";
    String contentType = "Content-Type: application/json";

    // Static Header

    @POST("login")
    @Headers({
            contentType,
            authorization
    })
    Call<ResObj> login(@Body UserCredential userCred);

    // Dynamic Header

    @POST("login")
    Call<ResObj> login(@Header("Authorization") String basicAuth, @Body UserCredential userCred);
}

The Body model can be:

public class UserCredential {
    private String username, password;

    public String getPassword() {
       ...encrypt your password here...
       return encrypted_password;
    }

}

Also, it is safe to put a null check before you do this: response.body(); in the API response.

Shirish Kadam
  • 689
  • 1
  • 9
  • 21
  • btw my main concern is basic auth, not the input username and password given by user. so your answer is about basic auth or login? if yes, where I need to put this? – Nurdin Jan 18 '18 at 18:47
  • 1
    @MohammadNurdin please check the API, I have added the Authorization header. This is a static header you can also add a dynamic one too. – Shirish Kadam Jan 18 '18 at 18:52
  • i will try it first – Nurdin Jan 18 '18 at 19:01
  • btw I'm not really understand how to embed into my existing code. can show me the full code based on my coding? – Nurdin Jan 19 '18 at 02:10
  • It's simple just add the headers to your APIs in your interface. I have updated the code. – Shirish Kadam Jan 19 '18 at 20:05