I successfully consume a json without password protected but admin set a password and I cannot get data via Retrofit2. How can I fix this? Please share your ideas. Thanks.
Configure your OkHttpClient with a new Authenticator to handle Basic Auth as follows:
OkHttpClient client = new OkHttpClient.Builder()
.authenticator(new Authenticator() {
#Override
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic("username", "password");
return response.request().newBuilder()
.header("Authorization", credential)
.build();
}
}).build();
Then use the OkHttpClient in Retrofit as follows:
new Retrofit.Builder()
.baseUrl("url")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
Related
I have been searching for the proper way to refresh token after the token generated by the AWS as Federated Identity has expired. My application uses cognito to log, and sign up users and then take the Access Token and then hit the apis using RetroFit.
Retrofit call
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
//end
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.readTimeout(45, TimeUnit.SECONDS);
httpClient.connectTimeout(120, TimeUnit.SECONDS);
httpClient.interceptors().add(new AuthInterceptor());
httpClient.addInterceptor(interceptor); //debugging
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
// Customize the request
Request request = original.newBuilder()
.header("Content-type", "application/json")
.header("Authorization", "auth-token")
.header("Accept", "application/json")
.header("deviceType", "android") //experimental
.header("Version", "v1")
.method(original.method(), original.body())
.build();
Response response = chain.proceed(request);
return response;
}
});
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.client(httpClient.build())
.addConverterFactory(ToStringConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(RetroInterface.class);
AuthInterceptor
...
if (jsonObject.getInt("status") == 0 && jsonObject.getJSONObject("data").getInt
("code")
== 99) {
IS_TOKEN_EXIPRED = true;
// HashMap<String, String> logins = new HashMap<String, String>();
logins.put("cognito-idp.us-east-1.amazonaws.com/" + BuildConfig.USERPOOLID,
Cognito.getInstance().getCurrSession().getIdToken().getJWTToken());
CognitoLogin.credentialsProvider.setLogins(logins);
String newtoken = Cognito.getInstance().getCurrSession().getAccessToken().getJWTToken();
Log.e("refy", newtoken);
BaseApplication.getApp().doSaveSharedString(AppConstants.USER_ACCESS_TOKEN, newtoken);
BaseApplication.getApp().doWriteLog("AuthInterceptor Here: ");
}
} catch (JSONException e) {
BaseApplication.getApp().redirectToLoginActivity();
e.printStackTrace();
}
...
I am stuck this problem., The token expires in 1 hour and then I cant do anything. There is not information available to refresh token in Android. All I can see is that Android AWS SDK refreshes the token by itself as long as Refresh Token as validity.
So after searching online for three days, I got the answer.
All you have to do is call the getSession(..) to get the refreshed tokens.
Here how it is done:
Cognito.getPool().getUser().getSession(new CognitoLogin(BaseApplication.getApp().getApplicationContext(), Cognito.getCurrUser(), Cognito.getPasswordForFirstTimeLogin()));
String newtoken = Cognito.getInstance().getCurrSession().getAccessToken().getJWTToken();
Reference
Cognito User Pool: How to refresh Access Token Android
I have a strange problem with one of my retrofit call,it works fine when the app is in the background(recent list)
I have a call through which i update my widget data,the problem is when the app is cleared of from the recent list,the call gives HTTP 401 unauthorized response.
however i pass the same bearer token with it.
please have a look at the code and suggest some help
public static OkHttpClient getOkhttpClient() {
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder()
.addHeader("Authorization", "Bearer " + TokenGenerator.getToken())
.build();
return chain.proceed(newRequest);
}
}).build();
return client;
}
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(getOkhttpClient())
.addConverterFactory(JacksonConverterFactory.create())
.build();
}
return retrofit;
}
Now i need to get thing shadow from aws-iot api.so when i hit same request into postman got 200ok in response.
From the app-side i got 403 i.e.forbidden.
Here i used "okhttp client" for fetch the request.
also attached image where i got 200ok response.
Now what i do from app side?I think its permission issue but not able to resolved please suggest.
also attached code as follows:-
Interceptor interceptor = new Interceptor() {
#Override
public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException {
Request newRequest = chain.request()
.newBuilder()
.addHeader("content-type", "application/x-www-form-urlencoded")
.addHeader("host", "ag7fce49bf5ti.iot.us-east-1.amazonaws.com")
.addHeader("x-amz-date", "20160919T054450Z")
.addHeader("authorization", "AWS4-HMAC-SHA256 Credential=AKIAJ6XB3CLURFLV6ISQ/20160919/us-east-1/iotdata/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=af7cd8cee7dd4763cff3a1c8f91cdde1fa22cc68012248a694cee098981bc623")
.build();
return chain.proceed(newRequest);
}
};
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.interceptors().add(interceptor);
client = builder.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://ag7fce49bf5ti.iot.us-east-1.amazonaws.com/things/dm_project/shadow/")
//.addConverterFactory(client)
.client(client)
.build();
im trying to consume an api that has that authorization header, i can get a 200 response in Postman with all data but cant get it to work in retrofit
May be you need add the Token using OkHttp Interceptor.
OkHttpClient client = new OkHttpClient.Builder()
.addNetworkInterceptor(mTokenInterceptor)
.build();
then add it to Retrofit:
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl(base_url)
.build();
the mTokenInterceptor:
Interceptor mTokenInterceptor = new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (mToken != null) {
Request.Builder requestBuilder = request.newBuilder()
.addHeader("Authorization", mToken);
Request newRequest = requestBuilder.build();
return chain.proceed(newRequest);
}
return chain.proceed(request);
}
};
when you get the Token, just assign the mToken,
You can try something like below, just a crude example
#GET("your server url goes here")
Call<Your_Model_Class> getServerData(#Header("Authorization") String token);
Pass your token to getServerData method.
I want to add facebook access token into retrofit (2 beta 3) request, but the access token does not added.
I can add interceptor to retrofit 1.9 successfully but in retrofit 2 it has error, Is there any solution?
protected Retrofit getRestAdapter() {
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(
new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
String sessionId = getSessionId(); // get access token
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.header("Cookie", sessionId)
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
})
.build();
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl("http://tbkha.com/api/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
}
return retrofit;
}
In retrofit retrofit 2.0 you add intercepter like this:
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(logging).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseURL)
.client(client)
.build();
Check this link for details https://futurestud.io/blog/retrofit-2-log-requests-and-responses
Similar questions:
App crash on HttpLoggingInterceptor
Retrofit2 HttpLoggingInterceptor Logcat