AYUDA EN LÍNEA
 WINDEVWEBDEV Y WINDEV MOBILE

Este contenido se ha traducido automáticamente.  Haga clic aquí  para ver la versión en inglés.
Ayuda / WLanguage / Funciones WLanguage / Comunicación / Gestión del protocolo OAuth 2.0
  • Properties specific to OAuth2Parameters variables
  • Modo de funcionamiento de la autenticación OAuth 2.0
  • PKCE authentication
WINDEV
WindowsLinuxUniversal Windows 10 AppJavaReportes y ConsultasCódigo de Usuario (UMC)
WEBDEV
WindowsLinuxPHPWEBDEV - Código Navegador
WINDEV Mobile
AndroidWidget Android iPhone/iPadIOS WidgetApple WatchMac CatalystUniversal Windows 10 App
Otros
Procedimientos almacenados
The OAuth2Parameters type is used to define the information required to authenticate on a web service implementing the OAuth 2.0 standard. These characteristics can be defined and changed using different WLanguage properties.
This type of variable must be passed as parameter to AuthIdentify. If authentication is successful, this function returns an Variable of type AuthToken, which can be used to make authenticated requests to the Web service.
Remark: For more details on the declaration of this type of variable and the use of WLanguage properties, see Declaring a variable.
Ejemplo
// Example used to retrieve a token to perform a request on 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 ConfigurationType<>SITE>
// If you are not using a website, you need to specify a localhost redirect URL
OAuth2Params.RedirectionURL = "http://localhost:9874/"
<END>

// Ask for authentication: opens the login window
MyToken is AuthToken = AuthIdentify(OAuth2Params)

// Request authenticated on a Dropbox API
req is httpRequest
req.Method = httpPost
req.URL = "https://api.dropboxapi.com/2/files/list_folder"
req.AuthToken = MyToken // Authentication token
req.ContentType = "application/json"
vAPIParam is Variant
vAPIParam.path = "/Homework/math"
vAPIParam.recursive = False
vAPIParam.include_media_info = False
vAPIParam.include_deleted = False
vAPIParam.include_has_explicit_shared_members = False
req.Content = VariantToJSON(vAPIParam)

HTTPresponse is httpResponse = HTTPSend(req)
let Data = JSONToVariant(HTTPresponse.Content)
// Use the incoming data...
Observaciones

Properties specific to OAuth2Parameters variables

The following properties can be used to handle the information required to perform the authentication:
Property nameType usedEffect
AdditionalParametersCharacter stringParameters of the first authentication request. This string must be formatted as URL parameters.
AuthURLCharacter stringAuthorization URL to be used (first URL of OAuth 2.0 specification).
ClientIDCharacter stringClient ID provided by the service when registering the application.
ClientSecretCharacter stringSecret application access code. This code is provided by the service when registering the application.
GrantTypeConstantGrant type available. The possible values are:
  • gtClientCredentials: Authentication without login window. The access authorization is given to the application (not to the user). The token provided to access the resources of the application is linked to the application itself.
  • gtAuthorizationCode (Default value): The access authorization is given to the user. A login window appears to let users enter their username and password. The access token is linked to the user.
Novedad versión 2024
Option
Integer constantAuthentication options:
  • authDefault: OAuth authentication by default.
  • authPKCE: Authentication via PKCE (Proof Key for Code Exchange).
Remark: PKCE provides additional security compared to OAuth. In some cases, although PKCE is used, it may be necessary to specify the secret key (ClientSecret property). We advise you to check the information expected by the platform used.
RedirectionURLCharacter stringRedirection URL to use during the authentication mechanism.
WINDEVAndroid For a Windows or Android application, this URL must have the following format: "http://localhost:PortNumber". This value must be exactly the same as the one specified when declaring the application in the corresponding web service.
iPhone/iPad This property must be specified. It corresponds to the redirect URL scheme specified by the web service provider for iOS.
Examples:
  • for Facebook, the URL must have the following format: "fb<ClientID>://authorize/".
  • for Google, the URL must have the following format: "<iOS URL scheme>:/oauth2redirect", where:
    • <iOS URL scheme> corresponds to the value provided by Google when creating an OAuth client ID for iOS.
    • "/oauth2redirect" is an example of a value. This parameter can be any value starting with a single forward slash "/" (for example, "//oauth2redirect" is not supported).
WEBDEV - Código Servidor For a WEBDEV website, this URL is calculated automatically. Therefore, there is no need to assign the property.
This URL must be specified in the configuration of the authentication service provider application. It has the following format:
"http(s)://localhost/WD290AWP/WD290Awp.exe/
OAUTH2_RETURN".
HTTPS will be automatically used if necessary in the redirect URL.
If an HTTP proxy acts as an intermediary between the WEBDEV Application Server that hosts the site and the authentication server, the proxy must be configured to indicate the right protocol in the "Forwarded" HTTP environment variable.
ResponseTypeCharacter string or constantType of response expected. The possible values are:
  • oauth2ResponseTypeCode (or "Code"): The response is of type "Code".
  • oauth2ResponseTypeToken (or "Token"): The response is of type "Token".
The default value is oauth2ResponseTypeCode.
Remarks:
  • For a "personal" authentication, the response type must be "Token".
  • In the case of an authentication for an API or service (e.g. Google mail server), the response type must be "Code".
ScopeCharacter stringRequested permissions. The possible values are specific to the web service used.
The possible values must be separated by a space.
TokenURLCharacter stringURL for retrieving the access token to use (second URL of OAuth 2.0 standard).

Modo de funcionamiento de la autenticación OAuth 2.0

Las etapas de la autenticación OAuth 2.0 que realiza la función AuthIdentify son las siguientes:
  • Ejecución de una primera solicitud HTTP para pedir una autorización (URL de autorización especificada en la variable de tipo OAuth2Parameters).
  • Apertura de una ventana de autenticación OAuth 2.0. La ventana de autenticación la define cada servicio.
  • Tras la autenticación, el servidor devuelve un código de autorización para solicitar un token de acceso. Este código se añade en el parámetro de la segunda URL (URL del token de acceso especificado en la variable de tipo OAuth2Parameters).
  • Ejecución de la segunda solicitud HTTP para solicitar el token de acceso. El resultado es un buffer JSON que contiene, entre otros elementos, el token de acceso ("access_token") que se utilizará para las solicitudes que requieran autenticación. La variable de tipo AuthToken contiene la información que se encuentra en el buffer JSON. Este token de acceso será utilizado por las llamadas a las API del servicio web.
Para usar las API del servicio web, utilice la función HTTPSend con una variable de tipo httpRequest que define la solicitud a ejecutar.
La variable AuthToken se asignará a la propiedad AuthToken de la variable httpRequest (ver ejemplo).
En este caso, el servidor recibirá el encabezado HTTP "Authorization" con un valor en el siguiente formato: "Autorización: Bearer xxx_access_token_xxx".
Atención:
  • Si el servidor no devuelve el token de acceso en formato de código JSON según el estándar OAuth2.0, se producirá un error y no se obtendrá el token. La respuesta del servidor se puede obtener mediante la propiedad ServerResponse de la variable de tipo AuthToken.
  • Si el servidor no soporta el encabezado HTTP "Authorization" para transmitir el token de acceso, el desarrollador debe realizar la transmisión según el formato esperado por el servicio solicitado.
    El siguiente ejemplo permite utilizar el servicio Web de Facebook. En este caso, el token de acceso debe especificarse en la URL de la solicitud.
    • WINDEVAndroid Ejemplo de código para 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 Ejemplo de código para 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
Novedad versión 2024

PKCE authentication

PKCE authentication example:
OAuth2Params is OAuth2Parameters
OAuth2Params.ClientID = "D90iXZWlteM3ESORkGkoWyGkJuxifE1z"
OAuth2Params.Option = authPKCE
OAuth2Params.AuthURL = "https://dev-rw5r4o2eowb8s70k.us.auth0.com/authorize"
OAuth2Params.TokenURL = "https://dev-rw5r4o2eowb8s70k.us.auth0.com/oauth/token"
OAuth2Params.RedirectionURL = "http://localhost:9874"
OAuth2Params.Scope = "openid email"

MonToken is AuthToken = AuthIdentify(OAuth2Params)
IF MonToken <> Null _AND_ NOT ErrorOccurred THEN
MonIdentité is OpenIDIdentity = OpenIDReadIdentity(MonToken)
IF MonIdentité.Valid THEN
Trace(MonIdentité.Email)
Trace(MonIdentité.Name)
Trace(MonIdentité.FirstName)
END
ELSE
Info("Echec" + ErrorInfo(errFullDetails))
END
Versión mínima requerida
  • Versión 22
Esta página también está disponible para…
Comentarios
Haga clic en [Agregar] para publicar un comentario

Última modificación: 08/03/2024

Señalar un error o enviar una sugerencia | Ayuda local