简体   繁体   中英

Retrofit Authorization Header with credentials

I have a web server where a directory and its contents are protected via htaccess. My Android app can access this directory with a username and password via OkHttpClient interceptor. At the moment, the actual username and password is set as parameters in the interceptor. The app is able to access without any issues.

My question is whether this is a good and safe practice. My code as below. Thank you in advance.

OkHttpClient

    //This method establish the OkHttpClient timers
private static OkHttpClient client() {
    //Return the OkHttpClient with the read and connect Timeouts
    return new OkHttpClient.Builder().readTimeout(30, TimeUnit.SECONDS)
            .connectTimeout(10, TimeUnit.SECONDS)
            .addInterceptor(new BasicAuthInterceptor("<username>","<password>"))
            .build();
}

BasicAuthInterceptor

public class BasicAuthInterceptor implements Interceptor {

private String credentials;

public BasicAuthInterceptor(String user, String password) {
    this.credentials = Credentials.basic(user, password);
}

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    Request authenticatedRequest = request.newBuilder()
            .header("Authorization", credentials).build();
    return chain.proceed(authenticatedRequest);
}

}

It's not ideal, but you work with the server and client stack you have. If auth on the server is client/password, and you prompt the user to enter the details and store, and the connections are always secure (https) then it seems optimal for your situation.

Things to avoid

  • plain text requests (http://)
  • embedding credentials in the app binary
  • using this for critical data since it's likely hard to revoke for a user, tokens like oauth are better for this, can be scoped also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM