2019-01-14
How can I change the bearer token in Moya
stackoverflow
Question

the documentation shows how to make targets require bearer tokens, which I did like this

extension MyService: AccessTokenAuthorizable {
    var authorizationType: AuthorizationType {
        switch self {
        case .resetPassword, .postTextBook, .bookmarkBook, .getBookmarks, .logout, .verify:
            return .bearer
        default:
            return .none
        }
    }
}

then it shows how to add tokens to the providers, which I did like this

let token = "abc123"
let authPlugin = AccessTokenPlugin(tokenClosure: token)
let provider = MoyaProvider<MyService>(plugins: [authPlugin])

but when the token expires, how can I change the token? and does Moya offer a way to automate this process, where if I get a forbidden http response (meaning I am not authorized), it automatically requests a token?

Answer
1

The implementation details of authentication/authorization can be quite different for each API out there. This is the reason why Moya will not handle the auth for you.

That said, implementing your own authentication/authorization can be done in many ways. It will depend on your constraints and/or preferences. As of today, you can find a few solutions sparsely outlined in Moya documentation:

  • Use the PluginType to add your auth to the requests. But think that this can potentially be used to refresh the token if needed. You may also need to intercept the completion of the request to detect authorization errors and apply your preferred recovery scenario (eg. refresh the token and retry the call).
  • Same can be implemented using the endpointClosure and/or requestClosure.
  • You can also consider implementing Alamofire's RequestAdapter and RequestRetrier. Depending on your needs, this can make retries easier. However, on them you will not have straightforward access to your TargetType, so you may need to find a way to recognize the different auth methods needed (ie. your bearer or none).

A few direct references to their documentation:

Also, I highly encourage anybody to learn/get inspiration from Eilodon's Networking source code.

How can I change the bearer token in Moya
See more ...