i am developing android application in Java i use native authentification for the login with the API KEY. username and password encoded base 64 : key: MAXAUTH value: nom:password(encoded 64) and the response is as cookie (set-cookies) header Someone can help me with code How can i do combine the username and password in base64 and use them then how can i use the set-cookie
2 Answers
Do you mean Basic Authentication.
If so then all you need is the Authorization header with the value being the Base64 encoded username:password combo prefixed with the string "Basic " For example if the username is foo and the password is bar then the Base64 encoded string is Zm9vOmJhcg== so you would pass the header Authorization: Basic Zm9vOmJhcg== as part of your request.
Also could you share a code snippet of how you're currently doing it?
- 2,407
- 2
- 12
- 19
-
No i use native authentification: for headers: key: MAXAUTH and value: username:password(encoded64) – Ahmed feki May 12 '21 at 06:38
-
Your question can be divided into two parts:-
- Encode Username and Password into base64
- Send Login Request and handle response
Please refer to these guide
- Base 64 encode and decode example code
- Consuming APIs with Retrofit
- Retrofit 2: Get JSON from Response body
1. Encode Username and Password into base64
private String encodeToBase64(String username, String password) {
String text = username + ":" + password;
byte[] data = text.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
return base64;
}
2. . Send Login Request and handle response
Create the retrofit instance
// Trailing slash is needed
public static final String BASE_URL = "http://api.myservice.com/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Api api = retrofit.create(Api.class);
Define the endpoints
public interface Api {
// Request method and URL specified in the annotation
@POST("login")
Call<ResponseBody> loginUser(
@Header("MAXAUTH") String apiKey
);
}
Consume the endpoint
String username = "...";
String password = "...";
String base64APIKey = encodeToBase64(username, password);
Call<Result> call = api.loginUser(base64APIKey);
call.enqueue(new Callback<Result>() {
@Override
public void onResponse(Call<Result> call, Response<Result> response) {
if(response.isSuccessful()) {
response.body(); // have your all data
// Handle Success Response
} else {
response.errorBody(); // Has your error response body
// Handle Error Response
}
@Override
public void onFailure(Call<Result> call, Throwable t) {
// Handle Network Errors or Exceptions here.
}
});
Word of caution:- Base64 is not an encryption method, its an encoding method and can be decoded. This means your API_KEY can easily be decoded and username/password can easily be extracted thus making it insecure.
- 118
- 9