Skip to content

Authenticated Rest Client

pyricau edited this page May 25, 2012 · 5 revisions

Since AndroidAnnotations 2.2

Authentication with @Rest

Please start by reading the Rest API documentation.

AndroidAnnotations @Rest annotation generates an implementation that uses Spring Android Rest Template.

Spring Android Rest Template already provides everything needed for request authentication, so let's use it!

Let's say we have the following rest client:

@Rest("http://some.server.com/services")
public interface RestClient {
    @Get("/events")
    EventList getEvents();
}

and a bean that stores authentication information:

@EBean(scope = Scope.Singleton)
public class MyAuthStore {
    public String getUsername() {
      return "H2G2";
    }

    public String getPassword() {
      return "42";
    }
}

We create a ClientHttpRequestInterceptor that will intercept every request:

@EBean(scope = Scope.Singleton)
public class MyAuthInterceptor implements ClientHttpRequestInterceptor {

    @Bean
    MyAuthStore authStore;

    public void ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        HttpHeaders headers = request.getHeaders();
        HttpAuthentication auth = new HttpBasicAuthentication(authStore.getUsername(), authStore.getPassword());
        headers.setAuthorization(auth);
        execution.execute(request, body);
    }
}

Then, it's just a matter of manually adding the ClientHttpRequestInterceptor to the RestTemplate used by our RestClient:

@EActivity
public class MyActivity extends Activity {

    @RestService
    RestClient client;

    @Bean
    MyAuthInterceptor authInterceptor;

    @AfterInject 
    void initAuth() {
        RestTemplate template = client.getRestTemplate();
        template.setInterceptors(Arrays.asList(authInterceptor));
    }
}

We agree that manual binding is not perfect, and we may provide better ways in the future

Using AndroidAnnotations

Questions?

Enjoying AndroidAnnotations

Improving AndroidAnnotations

Clone this wiki locally