We go in parts: Read well the official documentation of any API, library, there you will find everything you need.
In the official documentation of Twitter it says very clearly the following:
To generate the token you need to create the string in Base 64 of
consumerKey + consumerSecret, formatted as follows consumerKey: consumerSecret.
So, we have:
consumerKey: "VTkUsZX4Yqzlzlu6MBLdcIJoP",
consumerSecret: "1TdkkuboBIJjEOZsOk7NIiFlQbLtfAf1Lbvgqp72qLfGLXDACf",
This is transformed under the format of consumerKey:consumerSecret
var preparandoCadena = "VTkUsZX4Yqzlzlu6MBLdcIJoP:1TdkkuboBIJjEOZsOk7NIiFlQbLtfAf1Lbvgqp72qLfGLXDACf";
You apply some swift method to generate Base 64 of the previous variable.
And as a result you have:
VlRrVXpTWDRZcXpsemx1Nk1CTGRjSUpvUDoxVGRra3Vib0JJSmpFT1pzT2s3TklpRmxRYkx0ZkFmMUxidmdcxDI3cUxmR0xYREFDZg==
Now, in the headers you need to pass:
key: Authorization
value: Basic VlRrVXpTWDRZcXpsemx1Nk1CTGRjSUpvUDoxVGRra3Vib0JJSmpFT1pzT2s3TklpRmxRYkx0ZkFmMUxidmdcxDI3cUxmR0xYREFDZg==
In the body of the request:
key: grant_type
value: client_credentials
Using Postman I make the request and here I introduce you to your token:
{
"token_type": "bearer",
"access_token": "AAAAAAAAAAAAAAAAAAAAAA160QAAAAAAuxypuPwkbAfAqtdE2Px7ps%2By3%2FM%3DPKX1Cs6lhrm8Pk7HZH7YkeEH0V6vEPeHWrnraIuaDBziwIIWqR"
}
Reset a new key for security reasons. If this example does not work for you, it's because I changed the content of the keys.
Finally to use some function of the twitter API, in the documentation it says that we must add the Bearer token.
key: Authorization
value: Bearer AAAAAAAAAAAAAAAAAAAAAA160QAAAAAAuxypuPwkbAfAqtdE2Px7ps%2By3%2FM%3DPKX1Cs6lhrm8Pk7HZH7YkeEH0V6vEPeHWrnraIuaDBziwIIWqR
Note that there is a space between Bearer and {token}
PS: A while ago I also played with the Twittera API resulting in an engine that feeds my library of bookmarks that I get from twitter: link
Through OAUTH2 on SWIFT:
It turns out that you only had to modify the class OAuth2CodeGrant
to add in the client_secret that was not happening during the code exchange for the token:
open func accessTokenRequest(with code: String, params: OAuth2StringDict? = nil) throws -> OAuth2AuthRequest {
guard let clientId = clientConfig.clientId, !clientId.isEmpty else {
throw OAuth2Error.noClientId
}
guard let redirect = context.redirectURL else {
throw OAuth2Error.noRedirectURL
}
guard let clientSecret = clientConfig.clientSecret else {
throw OAuth2Error.noClientSecret
}
let req = OAuth2AuthRequest(url: (clientConfig.tokenURL ?? clientConfig.authorizeURL), method: .GET)
req.params["code"] = code
req.params["grant_type"] = type(of: self).grantType
req.params["redirect_uri"] = redirect
req.params["client_id"] = clientId
req.params["client_secret"] = clientSecret
return req
}
Reference of the latter: link