Sample code for 30+ languages & platforms
DataFlex

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 DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoRest
    Boolean iBTls
    Boolean iBAutoReconnect
    Variant vOauth2
    Handle hoOauth2
    String sResponseText
    String sTemp1
    Boolean bTemp1

    Move False To iSuccess

    Get Create (RefClass(cComChilkatRest)) To hoRest
    If (Not(IsComObjectCreated(hoRest))) Begin
        Send CreateComObject of hoRest
    End
    Move True To iBTls
    Move True To iBAutoReconnect
    Get ComConnect Of hoRest "example.com" 443 iBTls iBAutoReconnect To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoRest To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  Configure OAuth 2.0 bearer-token authentication.  The provider must contain a valid access token.
    Get Create (RefClass(cComChilkatOAuth2)) To hoOauth2
    If (Not(IsComObjectCreated(hoOauth2))) Begin
        Send CreateComObject of hoOauth2
    End
    //  Normally you would not hard-code secrets in source.  You should instead obtain them from an
    //  interactive prompt, environment variable, or a secrets vault.
    Set ComAccessToken Of hoOauth2 To "OAUTH2_ACCESS_TOKEN"

    //  Associate the provider so Chilkat adds the bearer token to the Authorization header.
    Get pvComObject of hoOauth2 to vOauth2
    Get ComSetAuthOAuth2 Of hoRest vOauth2 To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoRest To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get ComFullRequestNoBody Of hoRest "GET" "/api/resource" To sResponseText
    Get ComLastMethodSuccess Of hoRest To bTemp1
    If (bTemp1 = False) Begin
        Get ComLastErrorText Of hoRest To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Showln sResponseText


End_Procedure