ONLINE HELP
 WINDEVWEBDEV AND WINDEV MOBILE

This content has been translated automatically.  Click here  to view the French version.
Help / WLanguage / WLanguage functions / Communication / Managing the OAuth 2.0 protocol
  • Properties specific to AuthToken variables
  • Operating mode of OAuth 2.0 authentication
  • Using the AuthToken variables
WINDEV
WindowsLinuxUniversal Windows 10 AppJavaReports and QueriesUser code (UMC)
WEBDEV
WindowsLinuxPHPWEBDEV - Browser code
WINDEV Mobile
AndroidAndroid Widget iPhone/iPadIOS WidgetApple WatchMac CatalystUniversal Windows 10 App
Others
Stored procedures
The AuthToken type contains the characteristics of a token used to access a web service. This access token was requested beforehand:
  • by the AuthIdentify function.
  • by an HTTP request. In this case, the request returns the token in JSON format.
You can define and change the characteristics of this access token using different WLanguage properties.
Remark: For more details on the declaration of this type of variable and the use of WLanguage properties, see Declaring a variable.
Example
// Exemple permettant de récupérer un token pour effectuer une requête sur Dropbox
OAuth2Params is OAuth2Parameters
OAuth2Params.ClientID = "01234567890123456789" 
OAuth2Params.ClientSecret = "98765432109876543210"
OAuth2Params.AuthURL = "https://www.dropbox.com/oauth2/authorize"
OAuth2Params.TokenURL = "https://api.dropboxapi.com/oauth2/token"
OAuth2Params.AdditionalParameters = "force_reapprove=false"
<COMPILE IF TypeConfiguration<>Site>
//Si ce n'est pas dans un site WEB il faut une URL de redirection en localhost
OAuth2Params.RedirectionURL = "http://localhost:9874/"
<END>

// Demande d'authentification: ouvre la fenêtre de login
MonToken is AuthToken = AuthIdentify(OAuth2Params)

// Requête authentifiée sur une API de Dropbox
req is httpRequest
req.Method = httpPost
req.URL = "https://api.dropboxapi.com/2/files/list_folder"
req.AuthToken = MonToken // Token d'authentification
req.ContentType = "application/json"
vParamAPI is Variant
vParamAPI.path = "/Homework/math"
vParamAPI.recursive = False
vParamAPI.include_media_info = False
vParamAPI.include_deleted = False
vParamAPI.include_has_explicit_shared_members = False
req.Content = VariantToJSON(vParamAPI)

réponseHTTP is httpResponse = HTTPSend(req)
let Données = JSONToVariant(réponseHTTP.Content)
// Utilisation des données reçues ...
// Récupère le token (dans du JSON) via une requête HTTP. La fonction AuthIdentifie n'est pas utilisée
// Définition de la requête
httpReq is httpRequest
httpReq.Method = httpPost
httpReq.URL = PAYPAL_TOKEN
httpReq.User = PAYPAL_APP_ID
httpReq.Password = PAYPAL_SECRET
httpReq.Content = "grant_type=client_credentials"
httpReq.ContentType = "application/x-www-form-urlencoded"

// Exécution de la requête
httpRep is httpResponse = HTTPSend(httpReq)

// Récupération du token
IF httpRep.StatusCode = 200 THEN
// Déclare les paramètres, nécessaire pour le rafraîchissement du token
oAuth2Param is OAuth2Parameters
oAuth2Param.ClientID = PAYPAL_APP_ID
oAuth2Param.ClientSecret = PAYPAL_SECRET
oAuth2Param.AuthURL = PAYPAL_ACCESS_BASEURL
oAuth2Param.Scope = PAYPAL_SCOPES
oAuth2Param.TokenURL = PAYPAL_TOKEN

// Initialise le token avec le JSON
MonToken is AuthToken(oAuth2Param, httpRep.Content)
gMonToken <= MonToken
END
Syntax

Declaring an AuthToken variable Hide the details

MyVariable is AuthToken
In this case, AuthIdentify is used to retrieve the token parameters.

Declaring and describing an AuthToken variable (without using the AuthIdentify function) Hide the details

MyVariable is AuthToken(<OAuth2 parameter> , <Token>)
<OAuth2 parameter>: OAuthParameters variable
Name of OAuth2Parameters variable containing the information required to authenticate on a service implementing the OAuth 2.0 standard.
<Token>: Character string
String in JSON or UTF8 format containing the token. Corresponds to the token returned by the service.
Remarks

Properties specific to AuthToken variables

The following properties can be used to handle a token for accessing a web service:
Property nameType usedEffect
ExpirationDateDateTimeExpiration date and time of token.
Android This property is not available.
RefreshCharacter stringValue returned by the server to determine if the token can be refreshed.
If this property is not specified, AuthRefreshToken cannot be used to refresh the token: you will have to request a new token..
ServerResponseBufferValue returned by the server during the request made by the access token.
This property is read-only.
ValidBooleanValidity of access token:
  • True if the access token is valid.
  • False otherwise.
This property is read-only.
ValueCharacter stringAccess token.
Value automatically filled when using AuthIdentify.
This value can be used to send authenticated requests onto the relevant web service.

Operating mode of OAuth 2.0 authentication

The steps of OAuth 2.0 authentication performed by AuthIdentify are as follows:
  • Running a first HTTP request to ask for an authorization (authorization URL specified in the OAuth2Parameters variable).
  • Opening a window for user identification according to the OAuth 2.0 protocol. The identification interface is given by the service accessed.
  • After identification, the server returns a first authorization code allowing you to ask the resources for an access token. This code is added as parameter of second URL (access token URL specified in the OAuth2Parameters variable).
  • Running the second HTTP request to ask for the access token. The result is a JSON buffer that contains, among other things, the access token ("access_token") that will be used for the authenticated requests. The AuthToken variable contains the information found in this JSON buffer. This access token will be used by the calls to the APIs of Web service.
To use the APIs of the Web service, simply use the HTTPSend function with an httpRequest variable defining the query to be executed.
The AuthToken variable will be assigned to the AuthToken property of the httpRequest variable (see example).
In this case, the server will receive the HTTP "Authorization" header with a value in the following format: "Authorization: Bearer xxx_access_token_xxx".
Caution:
  • If the server does not return the access token in the format of JSON code according to the OAuth2.0 standard, an error will occur and the token will not be retrieved. The server response can be retrieved via the ServerResponse property of the AuthToken variable.
  • If the server does not support the HTTP "Authorization" header for transmitting the access token, this transmission must be done by the developer according to the format expected by the requested service.
    The following example allows you to use the Web service of Facebook. In this case, the access token must be specified on the request URL.
    • WINDEVAndroid Code sample for Facebook
      // Example used to retrieve the name of the Facebook account
      MyToken is AuthToken
      MyTokenParam is OAuth2Parameters

      MyTokenParam.ClientID = "123456789012345"
      MyTokenParam.ClientSecret = "45g8jh5kll45579021qsg5444j"
      MyTokenParam.AuthURL = "https://www.facebook.com/dialog/oauth"
      MyTokenParam.TokenURL = "https://graph.facebook.com/v2.3/oauth/access_token"
      MyTokenParam.RedirectionURL = "http://localhost:9874/"
      MyTokenParam.Scope = "email"

      MyToken = AuthIdentify(MyTokenParam)
      IF MyToken <> Null THEN
      IF ErrorOccurred THEN
      Error(ErrorInfo())
      ELSE
      // Token specified on the request URL
      HTTPRequest("https://graph.facebook.com/me?access_token=" + MyToken.Value)
      vMyRes is Variant = JSONToVariant(HTTPGetResult(httpResult))
      // Retrieve the account name
      Trace(vMyRes.name)
      END
      END
    • iPhone/iPad Code sample for Facebook:
      MyToken is AuthToken
      MyTokenParam is OAuth2Parameters
      MyTokenParam.ClientID = "1705548803004741"
      MyTokenParam.ClientSecret = "7b3305a5aa1687ef04af001ec3388ecc"
      MyTokenParam.AuthURL = "https://www.facebook.com/dialog/oauth"
      MyTokenParam.TokenURL = "https://graph.facebook.com/oauth/access_token"
      MyTokenParam.RedirectionURL = "fb1705548803004741://authorize/"
      MyTokenParam.Scope = "email"

      MyToken = AuthIdentify(MyTokenParam)
      IF MyToken <> Null THEN
      IF ErrorOccurred THEN
      Error(ErrorInfo())
      ELSE
      // Token specified on the request URL
      HTTPRequest("https://graph.facebook.com/me?access_token=" + MyToken.Value)
      vMyRes is Variant = JSONToVariant(HTTPGetResult(httpResult))
      // Retrieve the account name
      Trace(vMyRes.name)
      END
      END

Using the AuthToken variables

AuthToken variables can be used in the functions:
Minimum version required
  • Version 22
This page is also available for…
Comments
Click [Add] to post a comment

Last update: 12/02/2023

Send a report | Local help