Retrofit (2) — Token Authentication on Android

这篇的内容主要是对之前的[Basic认证]的补充,我们将讲一下在安卓app到服务器之间如何进行token认证.

Integrate Token Authentication 加入Token认证

如果你阅读过上一篇关于用Retrofit来进行认证的文章,那或许你就知道我们要做什么了:没错,就是拓展ServiceGenerate类,给它增加一个可以处理token认证的方法.我们又给ServiceGenerate类增添了一个creatService方法.

Retrofit1.9

public class ServiceGenerator {

    public static final String API_BASE_URL = "https://your.api-base.url";

    private static RestAdapter.Builder builder = new RestAdapter.Builder()
                .setEndpoint(API_BASE_URL)
                .setClient(new OkClient(new OkHttpClient()));

    public static <S> S createService(Class<S> serviceClass) {
        return createService(serviceClass, null);
    }

    public static <S> S createService(Class<S> serviceClass, final String authToken) {  
      if (authToken != null) {
          builder.setRequestInterceptor(new RequestInterceptor() {
              @Override
              public void intercept(RequestFacade request) {
                  request.addHeader("Authorization", authToken);
              }
          });
      }

      RestAdapter adapter = builder.build();
      return adapter.create(serviceClass);
    }
}

Retrofit2

public class ServiceGenerator {

    public static final String API_BASE_URL = "https://your.api-base.url";

    private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(API_BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create());

    public static <S> S createService(Class<S> serviceClass) {
        return createService(serviceClass, null);
    }

    public static <S> S createService(Class<S> serviceClass, final String authToken) {
        if (authToken != null) {
            httpClient.addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Interceptor.Chain chain) throws IOException {
                    Request original = chain.request();

                    /* Request customization: add request headers*/
                    Request.Builder requestBuilder = original.newBuilder()
                            .header("Authorization", authToken)
                            .method(original.method(), original.body());

                    Request request = requestBuilder.build();
                    return chain.proceed(request);
                }
            });
        }

        OkHttpClient client = httpClient.build();
        Retrofit retrofit = builder.client(client).build();
        return retrofit.create(serviceClass);
    }
}

仔细看上面的代码,我们把认证需要的token作为字符串变量传入这个方法,然后使用拦截器RequestInterceptor(Retrofit2中的是Interceptor)来向HTTP的头部字段来设置一个Authorization.
假如你的Token认证使用的是其他的HTTP头部字段,那就调整一下上面的代码,或者是新建一个方法来满足你的需求.

😃

现在,用这个加入了token值的方法创建的HTTP连接都会自动的发送token的值到API接受端.

Example Usage 用例

我们来把上面的代码用到实践当中看一下.下面的UserSevice 接口声明了一个me()方法,这个方法会返回一个根据API响应创建的user对象.

Retrofit1.9

public interface UserService {  
    @POST("/me")
    User me();
}

Retrofit2

public interface UserService {  
    @POST("/me")
    Call<User> me();
}

我们要访问的APIhttp://your.api-base.url/me需要一个认证,然后在响应中会返回用户数据.我们来创建一个UserSevice 对象,在实践请求中试一下.

Retrofit1.9

UserService userService =  ServiceGenerator.create(UserService.class, "auth-token");
User user = userService.me();

Retrofit2

UserService userService =  ServiceGenerator.create(UserService.class, "auth-token");
Call<User> call = userService.me();  
User user = call.execute().body(); 

这个代码只是演示了一下怎么使用,在实际应用中你要向ServiceGenerate方法提供一个真实的认证token.

翻译不当之处,请尽情指出,感激不尽.
原文:https://futurestud.io/tutorials/retrofit-token-authentication-on-android