Managing Authentication in Image Loading Using SDWebImage


Bearer tokens serve as a form of access token authentication, providing a secure method for authorizing API requests. They are typically included in the Authorization header of HTTP requests and grant access to protected resources.

We can bolster the security of loading our images using bearer tokens. Common SDWebImage’s extension method we use to load an image into UIImageView is:

imageView.sd_setImage(with: url, placeholderImage: nil, options: [.refreshCached]) { (image, error, cacheType, url) in
//Handle if required

How do we pass a bearer token in SDWebImage?

We use SDWebImageDownloaderRequestModifier protocol. It enables for adding the Bearer token to the header of outgoing requests. Once the custom request modifier is implemented, developers can set it as the request modifier for the SDWebImage downloader. By providing the Bearer token to the request modifier, we ensure that all subsequent image loading requests include the necessary authentication information in the header. In our example we add it to default shared singleton downloader.

let requestModifier = SDWebImageDownloaderRequestModifier { [weak self] (request) -> URLRequest? in
    if (request.url?.host == "") {
        var mutableRequest = request
        mutableRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        return mutableRequest
    return request

We are also adding token only to requests from our api’s endpoint only. For other requests we are not doing anything.

More Articles

Recommended posts