Swift oAuth 2.0 can't send request to get acces_token correctly

I want to use oAuth 2.0 from Openstreetmap.

  1. I go to auth_url and successfully get auth_code.
  2. I must send request to token_url for get access_token by swift.
    If i send post request with “nil” body, i get error 415. And if i send request with some body: fore example let data = Data(“1”.utf8) i get access_token successfully.
    Please, help me send request correctly.
    My code:
guard let url = URL(string: "https://www.openstreetmap.org/oauth2/token?grant_type=authorization_code&code=<MY_CODE>&redirect_uri=osmeditor:/&client_secret=<CLIENT_SECRET>&client_id=<CLIENT_ID>") else {return}
var request = URLRequest(url: url)
request.httpMethod = "POST"
let data = Data("1".utf8)
request.httpBody = data
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, _ in ...}

You need to send the parameters as JSON in the body, not in the URL as you are trying to do that.

But you know that because we discussed this last week in oAuth 2.0 can not get access_token - #5 by kadi4.

2 Likes

Note that 415 is Unsupported Media Type because your body is not of the right type.

I think that server get my parameters from URL, but not from body.
I must send any headers if i send data in body?

Here is the OAuth 2 specification details of how to request an access token - you need to POST using the application/x-www-form-urlencoded content type - in other words normal HTTP form submission.

1 Like

how i understand, post request send data in http body.
But if i send paranetrs in url and add headers - content type : application/x-www-form-urlencoded
and go to url:
https://www.openstreetmap.org/oauth2/token?grant_type=authorization_code&code=CODE&redirect_uri=osmeditor:/&client_secret=CLIENT_SECRET&client_id=CLIENT_ID

it work good, i get access_token. Http body = nil, i don’t send data in body.

Is it correctly way?

if i make headers - content type : application/x-www-form-urlencoded
and send parametrs in body, go to url https://www.openstreetmap.org/oauth2/token, i get error 400