androidmapboxmapbox-android

How to provide an authentication token to a tile provider with Mapbox Android SDK v10-beta20?


To get my tiles I do:

style(styleUri = Style.MAPBOX_STREETS) {
    +vectorSource(id = "parcel-source") {
    url("http://example.com/{z}/{x}/{y}.png")
}

But I need to provide a token to a tile provider, with an HTTP header like Authorization: bearer [token].

The documentation shows a skeleton for an HTTP interceptor, but give little clue on how to implement the 5 functions of the interface to be implemented. I can't find the involved interface in the API reference neither. There is an open issue logged for a similar problem.

Also, a solution working for v9.5 seems not available anymore in v10 (HttpRequestUtil missing).


Solution

  • I ran into this issue when trying to use the HttpServiceInterface approach also described in the documentation. In v10 there is another option to use HttpServiceFactory.getInstance().setInterceptor. This interface is much simpler to implement and each method is expected to return the same object.

    This was my approach:

    class CustomMapboxIntercepter() : HttpServiceInterceptorInterface {
    
        override fun onRequest(request: HttpRequest): HttpRequest {
            request.headers["Authorization"] = "Bearer $token" 
            return request
        }
    
        override fun onDownload(download: DownloadOptions): DownloadOptions {
            return download
        }
    
        override fun onResponse(response: HttpResponse): HttpResponse {
            return response
        }
    }
    

    Then just setting the intercepter based on the class:

    HttpServiceFactory.getInstance().setIntercepter(CustomMapboxIntercepter())
    

    Using HttpServiceIntercepterInterface also makes it easier to have arguments in the constructor which is where the above mentioned issue occurs for me. It seems it will also be possible in v11 but with a small change to the API:

    Replace HttpServiceFactory.getInstance().setInterceptor with HttpServiceFactory.setHttpServiceInterceptor.