Waruna
Waruna

Reputation: 1174

Making oAuth authentication request from Swift iOS

How do I convert this oAuth curl request to swift syntax.

curl -X POST -vu clientapp:123456 http://localhost:8080/oauth/token -H "Accept: application/json" -d "password=spring&username=roy&grant_type=password&scope=read%20write&client_secret=123456&client_id=clientapp"

Upvotes: 1

Views: 805

Answers (1)

Waruna
Waruna

Reputation: 1174

I was able to achieve this by encoding user credential in base 64 string.

    let parameters = ["password" : "spring", "username" : "roy", "grant_type" : "password",
        "scope" : "read write", "client_secret" : "123456", "client_id" : "clientapp"]

    let str = "clientapp:123456"
    let utf8str = str.dataUsingEncoding(NSUTF8StringEncoding)
    let basic_auth_token = utf8str?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))


    let headers = ["Accept" : "application/json", "Authorization" :"Basic "+basic_auth_token!]
    Alamofire.request(.POST, "http://localhost:8080/oauth/token", parameters: parameters, encoding:.URL, headers: headers)
        .responseJSON { response  in
            print("Response String: \(response.result.value)")                
    }

Upvotes: 3

Related Questions