PureBasic
PureBasic
Configure OAuth 2.0 Authentication for REST
See more REST Examples
Demonstrates Rest.SetAuthOAuth2, which associates an OAuth2 provider containing a valid access token so Chilkat adds the bearer token to the Authorization header.
Background. OAuth 2.0 bearer-token authentication attaches the access token to each request. The token is typically obtained separately through an OAuth 2.0 authorization flow before being assigned to the provider.
Chilkat PureBasic Downloads
IncludeFile "CkRest.pb"
IncludeFile "CkOAuth2.pb"
Procedure ChilkatExample()
success.i = 0
rest.i = CkRest::ckCreate()
If rest.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
bTls.i = 1
bAutoReconnect.i = 1
success = CkRest::ckConnect(rest,"example.com",443,bTls,bAutoReconnect)
If success = 0
Debug CkRest::ckLastErrorText(rest)
CkRest::ckDispose(rest)
ProcedureReturn
EndIf
; Configure OAuth 2.0 bearer-token authentication. The provider must contain a valid access token.
oauth2.i = CkOAuth2::ckCreate()
If oauth2.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
; Normally you would not hard-code secrets in source. You should instead obtain them from an
; interactive prompt, environment variable, or a secrets vault.
CkOAuth2::setCkAccessToken(oauth2, "OAUTH2_ACCESS_TOKEN")
; Associate the provider so Chilkat adds the bearer token to the Authorization header.
success = CkRest::ckSetAuthOAuth2(rest,oauth2)
If success = 0
Debug CkRest::ckLastErrorText(rest)
CkRest::ckDispose(rest)
CkOAuth2::ckDispose(oauth2)
ProcedureReturn
EndIf
responseText.s = CkRest::ckFullRequestNoBody(rest,"GET","/api/resource")
If CkRest::ckLastMethodSuccess(rest) = 0
Debug CkRest::ckLastErrorText(rest)
CkRest::ckDispose(rest)
CkOAuth2::ckDispose(oauth2)
ProcedureReturn
EndIf
Debug responseText
CkRest::ckDispose(rest)
CkOAuth2::ckDispose(oauth2)
ProcedureReturn
EndProcedure