1

In python, we can authenticate a request like this

session = requests.session()
session.auth = ("xxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxx")
r = session.get('https://example.com/api/v1/method').json()

How can we do this in swift? Is there a built-in class for this?

Keoros
  • 1,337
  • 2
  • 13
  • 23

1 Answers1

1

This is a common authorization feature as known as Basic access authentication

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization https://en.wikipedia.org/wiki/Basic_access_authentication

It works this way. You append base64-encoded string in the request header for value "Authorization". This string has got this format :

So, for swift 4 you have to use this way:

let username = "user"
let password = "pass"
let loginString = String(format: "%@:%@", username, password)
let loginData = loginString.data(using: .utf8)!
let base64LoginString = loginData.base64EncodedString()

var request = URLRequest(url: url)
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

detailed example is here

https://stackoverflow.com/a/24380884/1979882

Vyacheslav
  • 26,359
  • 19
  • 112
  • 194