Search code examples
iosswiftauthenticationalamofiremoya

How to set basic auth username and password in Moya?


I've retrieved the username and password from a UITextField and now I want to set the username and password to every request Moya performs with basic auth.

How do I do this?


Solution

  • The documentation that covers Basic Authentication is here

    Here are the required parts you need

    HTTP auth is a username/password challenge built into the HTTP protocol itself. If you need to use HTTP auth, you can provide a CredentialsPlugin when initializing your provider.

    let provider = MoyaProvider<YourAPI>(plugins: [CredentialsPlugin { _ -> URLCredential? in
        return URLCredential(user: "user", password: "passwd", persistence: .none)
      }
    ])
    

    This specific examples shows a use of HTTP that authenticates every request, which is usually not necessary. This might be a better idea:

    let provider = MoyaProvider<YourAPI>(plugins: [CredentialsPlugin { target -> URLCredential? in
        switch target {
          case .targetThatNeedsAuthentication:
            return URLCredential(user: "user", password: "passwd", persistence: .none)
          default:
            return nil
        }
      }
    ])