androidoauth-2.0http-headershttp-authenticationspring-android

Spring fo Android : request authorization headers (not basic)


I have an app that uses Spring for Android on the Client side and Spring Boot on the Server side. We would like to add client authorization to some requests. We already use Firebase and OAuth2 and after reading on the subject, I feel like the best way to go would be to use the Authentification header to send the JWT to our server, with the bearer method for the authorization :

Authorization: Bearer <token>

Something like that ...

My problem is this : Spring for Android only has BasicAccessAuthentification built-in, but I dont have a username:password scheme for my client credentials, only a JWT. I quite naively tried creating a Class that extends HttpAuthentication :

import org.springframework.http.HttpAuthentication;

public class HttpBearerAuthentification extends HttpAuthentication {

  private String token;

  public HttpBearerAuthentification(String token){
    this.token = token;
  }

  public String getHeaderValue() {
    return String.format("Bearer %s", token);
  }

  @Override
  public String toString() {
    return String.format("Authorization: %s", getHeaderValue());
  }

}

This class is based on the HttpBasicAuthentication class in Spring for Android.

And then doing the request :

// regular request that I know works

...

HttpBearerAuthentification auth = new HttpBearerAuthentification(token);
headers.setAuthorization(auth)

...

// send request and get answer as usuall   

I know the requests themselves work (requests without without authorization, at least) so this is not the problem. Would that be the right way to do it ? I understand the success of the request also depends on how the server handle the request. But for now, my question is really about the client side. Is this code enough to send the JWT to the server ?


Solution

  • After some testing on requests sent with SpringForAndroid, it seems that is is quite easy to set values for headers. Because the HttpHeaders class actually implements the Map interface, all I had to do was :

    protected HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Bearer " + userRegistrationToken);