OAuth Class
Properties Methods Events Configuration Settings Errors
The OAuth class is used to authorize a client and provide an authorization string used in future requests.
Syntax
OAuth
Remarks
The OAuth class supports both plaintext and SSL/TLS connections. When connecting over SSL/TLS the SSLServerAuthentication event allows you to check the server identity and other security attributes. The SSLStatus event provides information about the SSL handshake. Additional SSL related settings are also supported via the Config method.
The OAuth class provides an easy way to obtain an authorization string for future requests to a service. The class implements an OAuth 2.0 client.
To begin using the class you will first need to register your application with the service you want to use. During this process you should obtain a ClientId and ClientSecret as well as the ServerAuthURL and ServerTokenURL for the authorization server. Then set ClientProfile to the client type that best describes your situation and call GetAuthorization.
The following client types are currently supported by the class:
- Application (desktop application)
- WebServer (server side application such as a web site)
- Device (an application without browser access such as a game console)
- Mobile (phone or tablet application)
- Browser (javascript application)
- JWT (server to server authentication using a JWT bearer token such as Google service account authentication)
Application Client Type
The application client type is applicable to applications that are run by the user directly. For instance a windows form application would use the application client type. To authorize your application (client) using the application client type follow the steps below.First, set ClientProfile to cfApplication. This defines the client type the class will use. Set the ClientId, ClientSecret, ServerAuthURL, and ServerTokenURL to the values you obtained when registering your application.
Next, call GetAuthorization to begin the authorization process. When GetAuthorization is called the class will build the URL to which the user will be directed and fire the LaunchBrowser event. The class will then launch the browser using the command and URL shown in the LaunchBrowser event.
The user will authenticate to the service, and then be redirected back to an embedded web server that was automatically started when GetAuthorization was called. At this time the ReturnURL event will fire. This event provides an opportunity to provide a custom response to your user that they will see in their browser.
The class will then automatically exchange the grant that was returned by the authorization server for the access token using the HTTP endpoint specified in ServerTokenURL.
The authorization is now complete and the GetAuthorization method will return the authorization string. To use the authorization string with any of our classs simply pass this value to the Authorization property before making the request.
A simple example is shown below.
component.ClientId =
"MyId"
;
component.ClientSecret =
"MyPassword"
;
component.ServerAuthURL =
"https://accounts.google.com/o/oauth2/auth"
;
component.ServerTokenURL =
"https://accounts.google.com/o/oauth2/token"
;
HTTP.Authorization = component.GetAuthorization();
HTTP.Get(
"https://www.googleapis.com/oauth2/v1/userinfo"
);
WebServer Client Type
The WebServer client type is applicable to applications that are run on the server side where the user uses the application from a web browser. To authorize your application (client) using this client type follow the steps below.
First, set ClientProfile to cfWebServer. This defines the client type the component will use. Set the ClientId, ClientSecret, ServerAuthURL, and ServerTokenURL to the values you obtained when registering your application. Set ReturnURL to the page on your site that will be the endpoint the user is redirected back to after authentication.
Next, call GetAuthorizationURL. This will return a URL to which the user should be redirected. Redirect the user to this URL.
After the user authenticates and is returned to the page on your site specified by ReturnURL, parse the "code" query string parameter from the incoming request. Set AuthorizationCode to this value.
Call GetAuthorization to exchange the code specified in AuthorizationCode for a token from the server specified by ServerTokenURL. GetAuthorization returns the authorization string. To use the authorization string with any of our components simply pass this value to the Authorization property before making the request.
Device Client Type
The Device client type is applicable to applications that are run on devices where no web browser can be used. For instance a game console would use the device client type. To authorize your application (client) using the device client type follow the steps below.
First, set ClientProfile to cfDevice. This defines the client type the class will use. Set the ClientId, ClientSecret, ServerAuthURL, and ServerTokenURL to the values you obtained when registering your application. Do not set ReturnURL.
Next, call GetAuthorizationURL. The class will automatically make a request to ServerAuthURL to obtain a user code for the device. The GetAuthorizationURL method will return the URL your user must visit from another device or computer that has web browser support. The GetAuthorizationURL method will also populate DeviceUserCode. This device user code must also be provided to the user. The user will enter the code at the URL returned by GetAuthorizationURL.
At this time, call GetAuthorization. The class will begin polling the server specified in ServerTokenURL. The polling interval is specified (in seconds) by the PollingInterval setting.
After the user has authenticated, the GetAuthorization method will return the authorization string. To use the authorization string with any of our components simply pass this value to the Authorization property before making the request.
Mobile Client Type
The Mobile client type is applicable to applications that are run on devices where a web browser can be used. For instance a mobile phone or tablet. The behavior when using this client type is very similar to the Application client type. The only difference between the Mobile and Application client types is the way the browser is launched, when set to Mobile the LaunchBrowser event will fire but the class will not attempt to launch the browser automatically. The browser must be launched manually from code. This behavior is the only difference between the Mobile and Application client type. Please read the steps above for the Application client type for a more detailed look at the process.
JWT Bearer Token (Server to Server) Type
The JWT (JSON Web Token) Bearer Token type is available for server to server authentication. For instance this may be used by web applications to access a Google service. In this case the application will access data on behalf of the service account, not the end user. End user interaction is not required.
First, specify AuthorizationScope ServerTokenURL and JWTServiceProvider.
Next specify JWT specific values. The use of the JWT profile also requires additional configuration settings to be specified, including a certificate with private key used to sign the JWT. Either specify the JWTJSONKey configuration setting, which will parse the necessary information automatically, or manually specify the following configuration settings:
- JWTIssuer (required)
- JWTAudience (required)
- JWTCertStoreType (required)
- JWTCertStore (required)
- JWTCertStorePassword (required)
- JWTCertSubject (required)
- JWTSubject
- JWTValidityTime
- JWTSignatureAlgorithm
Example (Google):
oauth.AuthorizationScope =
"https://www.googleapis.com/auth/analytics"
;
oauth.ServerTokenURL =
"https://www.googleapis.com/oauth2/v3/token"
;
oauth.ClientProfile = OauthClientProfiles.cfJWT;
oauth.Config(
"JWTServiceProvider=0"
);
oauth.Config(
"JWTIssuer=111917875427-g39d5bar90mjgiuf2n5ases9qk0j2q0p@developer.gserviceaccount.com"
);
oauth.Config(
"JWTAudience=https://www.googleapis.com/oauth2/v3/token"
);
oauth.Config(
"JWTCertStoreType=2"
);
oauth.Config(
"JWTCertStore=C:\\MyCertificate.p12"
);
oauth.Config(
"JWTCertStorePassword=password"
);
oauth.Config(
"JWTCertSubject=*"
);
oauth.Config(
"JWTValidityTime=5400"
);
//in seconds
string
authStr = oauth.GetAuthorization();
Example (Microsoft):
oauth.ClientId =
"Client_Id"
;
oauth.ClientProfile = OauthClientProfiles.cfJWT;
oauth.AuthorizationScope =
"https://graph.microsoft.com/.default"
;
oauth.ServerTokenURL =
"https://login.microsoftonline.com/"
+ tenant_id +
"/oauth2/V2.0/token"
;
oauth.Config(
"JWTCertStoreType=2"
);
oauth.Config(
"JWTCertStore=C:\\MyCertificate.p12"
);
oauth.Config(
"JWTCertStorePassword=password"
);
oauth.Config(
"JWTCertSubject=*"
);
oauth.Config(
"JWTValidityTime=3600"
);
oauth.Config(
"JWTAudience=https://login.microsoftonline.com/"
+ tenant_id +
"/oauth2/V2.0/token"
);
string
authStr = oauth.GetAuthorization();
Microsoft Admin Consent Type
The Microsoft Admin Consent type is used when setting up application permissions for apps that authenticate to Microsoft. Typically this type is used in the client credentials grant flow so that the admin can consent to the scopes that are defined by the App's registration in Azure Portal. After the app has been registered, the Application (client) ID will need to be set to the ClientId property. Also, a registered return URL must be set to the ReturnURL property.
When the GetAuthorization method is called, the class will fire the LaunchBrowser event and open the admin consent page URL (eg. https://login.microsoftonline.com/common/adminconsent?client_id=CLIENT_ID&redirect_uri=URL). At the same time, the class will start an embedded webserver that will be used to receive the results from the redirect URI.
If the Admin consents to the scopes, the redirect URI will supply the tenant ID of the admin. The tenant ID can be accessed through the Microsoft365AdminConsentTenant configuration and is often needed for authenticating a client later (eg. Client Credentials Grant Flow). Once the Admin consents once, they typically will not need to go through the process again unless the scopes of the application change.
If the Admin does not consent to the scopes, the redirect URI will give an error message and a description of the error. The error message can be found in the Microsoft365AdminConsentError configuration setting and the error description can be found in the Microsoft365AdminConsentErrorDesc configuration setting. Additionally the class fails with an error.
For example:
oauth.ClientId =
"Client_ID"
;
oauth.ClientProfile = OauthClientProfiles.cfMicrosoft365AdminConsent;
oauth.WebServerPort = 8888;
oauth.ReturnURL =
"http://localhost:8888"
;
oauth.GetAuthorization();
string
tenant = oauth.Config(
"Microsoft365AdminConsentTenant"
);
Property List
The following is the full list of the properties of the class with short descriptions. Click on the links for further details.
AccessToken | The access token returned by the authorization server. |
AuthorizationCode | The authorization code that is exchanged for an access token. |
AuthorizationScope | The scope request or response parameter used during authorization. |
ClientId | The id of the client assigned when registering the application. |
ClientProfile | The type of client that is requesting authorization. |
ClientSecret | The secret value for the client assigned when registering the application. |
Connected | Shows whether the class is connected. |
CookieCount | The number of records in the Cookie arrays. |
CookieDomain | The domain of a received cookie. |
CookieExpiration | This property contains an expiration time for the cookie (if provided by the server). |
CookieName | The name of the cookie. |
CookiePath | This property contains a path name to limit the cookie to (if provided by the server). |
CookieSecure | This property contains the security flag of the received cookie. |
CookieValue | This property contains the value of the cookie. |
FirewallAutoDetect | This property tells the class whether or not to automatically detect and use firewall system settings, if available. |
FirewallType | This property determines the type of firewall to connect through. |
FirewallHost | This property contains the name or IP address of firewall (optional). |
FirewallPassword | This property contains a password if authentication is to be used when connecting through the firewall. |
FirewallPort | This property contains the TCP port for the firewall Host . |
FirewallUser | This property contains a user name if authentication is to be used connecting through a firewall. |
FollowRedirects | Determines what happens when the server issues a redirect. |
GrantType | The OAuth grant type used to acquire an OAuth access token. |
Idle | The current status of the class. |
LocalHost | The name of the local host or user-assigned IP interface through which connections are initiated or accepted. |
OtherHeaders | Other headers as determined by the user (optional). |
ParamCount | The number of records in the Param arrays. |
ParamName | This property contains the name of the parameter to be used in the request or returned in the response. |
ParamValue | This property contains the value of the parameter to be used in the request or returned in the response. |
ProxyAuthScheme | This property is used to tell the class which type of authorization to perform when connecting to the proxy. |
ProxyAutoDetect | This property tells the class whether or not to automatically detect and use proxy system settings, if available. |
ProxyPassword | This property contains a password if authentication is to be used for the proxy. |
ProxyPort | This property contains the TCP port for the proxy Server (default 80). |
ProxyServer | If a proxy Server is given, then the HTTP request is sent to the proxy instead of the server otherwise specified. |
ProxySSL | This property determines when to use SSL for the connection to the proxy. |
ProxyUser | This property contains a user name, if authentication is to be used for the proxy. |
RefreshToken | Specifies the refresh token received from or sent to the authorization server. |
ReturnURL | The URL where the user (browser) returns after authenticating. |
ServerAuthURL | The URL of the authorization server. |
ServerTokenURL | The URL used to obtain the access token. |
SSLAcceptServerCertEncoded | The certificate (PEM/base64 encoded). |
SSLCertEncoded | The certificate (PEM/base64 encoded). |
SSLCertStore | The name of the certificate store for the client certificate. |
SSLCertStorePassword | If the certificate store is of a type that requires a password, this property is used to specify that password in order to open the certificate store. |
SSLCertStoreType | The type of certificate store for this certificate. |
SSLCertSubject | The subject of the certificate used for client authentication. |
SSLServerCertEncoded | The certificate (PEM/base64 encoded). |
Timeout | A timeout for the class. |
TransferredData | The contents of the last response from the server. |
TransferredHeaders | The full set of headers as received from the server. |
WebServerPort | The local port on which the embedded web server listens. |
WebServerSSLCertStore | The name of the certificate store for the client certificate. |
WebServerSSLCertStorePassword | If the certificate store is of a type that requires a password, this property is used to specify that password in order to open the certificate store. |
WebServerSSLCertStoreType | The type of certificate store for this certificate. |
WebServerSSLCertSubject | The subject of the certificate used for client authentication. |
WebServerSSLEnabled | Whether the web server requires SSL connections. |
Method List
The following is the full list of the methods of the class with short descriptions. Click on the links for further details.
AddCookie | Adds a cookie and the corresponding value to the outgoing request headers. |
AddParam | Adds a name-value pair to the query string parameters of outgoing request. |
Config | Sets or retrieves a configuration setting. |
DoEvents | Processes events from the internal message queue. |
GetAuthorization | Gets the authorization string required to access the protected resource. |
GetAuthorizationURL | Builds and returns the URL to which the user should be re-directed for authorization. |
Interrupt | Interrupt the current method. |
Reset | Reset the class. |
StartWebServer | Starts the embedded web server. |
StopWebServer | Stops the embedded web server. |
Event List
The following is the full list of the events fired by the class with short descriptions. Click on the links for further details.
Connected | Fired immediately after a connection completes (or fails). |
ConnectionStatus | Fired to indicate changes in connection state. |
Disconnected | Fired when a connection is closed. |
EndTransfer | Fired when a document finishes transferring. |
Error | Information about errors during data delivery. |
Header | Fired every time a header line comes in. |
LaunchBrowser | Fires before launching a browser with the authorization URL. |
Log | Fires once for each log message. |
Redirect | Fired when a redirection is received from the server. |
ReturnURL | Fires when the user is redirected to the embedded web server. |
SetCookie | Fired for every cookie set by the server. |
SSLServerAuthentication | Fired after the server presents its certificate to the client. |
SSLStatus | Shows the progress of the secure connection. |
StartTransfer | Fired when a document starts transferring (after the headers). |
Status | Fired when the HTTP status line is received from the server. |
Transfer | Fired while a document transfers (delivers document). |
Configuration Settings
The following is a list of configuration settings for the class with short descriptions. Click on the links for further details.
AccessTokenExp | The lifetime of the access token. |
AuthorizationTokenType | The type of access token returned. |
AuthorizationURL | Specifies the URL used for authorization. |
BrowserResponseTimeout | Specifies the amount of time to wait for a response from the browser. |
CodeChallengeMethod | The code challenge method to use (if any). |
DeviceGrantType | The grant type to be used when the ClientProfile is set to cfDevice. |
DeviceUserCode | The device's user code when the ClientProfile is set to cfDevice. |
FormVarCount | Specifies the number of additional form variables to include in the request. |
FormVarName[i] | Specifies the form variable name at the specified index. |
FormVarValue[i] | Specifies the form variable value at the specified index. |
IncludeEmptyRedirectURI | Whether an empty redirect_uri parameter is included in requests. |
JWTAudience | The JWT audience when the ClientProfile is set to cfJWT. |
JWTCertStore | The name of the certificate store for the JWT signing certificate. |
JWTCertStorePassword | The JWT signing certificate password. |
JWTCertStoreType | The type of certificate store. |
JWTCertSubject | The JWT signing certificate subject. |
JWTIssuer | The JWT issuer when the ClientProfile is set to cfJWT. |
JWTJSONKey | The file path of the JWT JSON Key, or a string containing its content. |
JWTServiceProvider | The service provider to which authentication is being performed. |
JWTSignatureAlgorithm | The signature algorithm used to sign the JWT. |
JWTSubject | The subject field in the JWT. |
JWTValidityTime | The amount of time in seconds for which the assertion in the JWT is valid. |
Microsoft365AdminConsentError | The error message returned when the admin denies consent to the scopes. |
Microsoft365AdminConsentErrorDesc | The error description returned when the admin denies consent to the scopes. |
Microsoft365AdminConsentTenant | The tenant ID returned after the admin consents to the scopes. |
Office365ServiceAPIVersion | The API version of the Office 365 service being discovered. |
Office365ServiceCapability | The API capability of the Office 365 service being discovered. |
Office365ServiceEndpoint | The Office 365 endpoint for the service that matches the criteria specified. |
PasswordGrantUsername | The Username field when using the password grant type. |
PollingInterval | The interval in seconds between polling requests when the device client type is used. |
ReUseWebServer | Determines if the same server instance is used between requests. |
TokenInfoFieldCount | The number of fields in the tokeninfo service response. |
TokenInfoFieldName[i] | The name of the tokeninfo service response field. |
TokenInfoFieldValue[i] | The value of the tokeninfo service response field. |
TokenInfoURL | The URL of the tokeninfo service. |
ValidateToken | Validates the specified access token with a tokeninfo service. |
WebServerFailedResponse | The custom response that will be displayed to the user if authentication failed. |
WebServerHost | The hostname used by the embedded web server displayed in the ReturnURL. |
WebServerResponse | The custom response that will be displayed to the user. |
AcceptEncoding | Used to tell the server which types of content encodings the client supports. |
AllowHTTPCompression | This property enables HTTP compression for receiving data. |
AllowHTTPFallback | Whether HTTP/2 connections are permitted to fallback to HTTP/1.1. |
Append | Whether to append data to LocalFile. |
Authorization | The Authorization string to be sent to the server. |
BytesTransferred | Contains the number of bytes transferred in the response data. |
ChunkSize | Specifies the chunk size in bytes when using chunked encoding. |
CompressHTTPRequest | Set to true to compress the body of a PUT or POST request. |
EncodeURL | If set to true the URL will be encoded by the class. |
FollowRedirects | Determines what happens when the server issues a redirect. |
GetOn302Redirect | If set to true the class will perform a GET on the new location. |
HTTP2HeadersWithoutIndexing | HTTP2 headers that should not update the dynamic header table with incremental indexing. |
HTTPVersion | The version of HTTP used by the class. |
IfModifiedSince | A date determining the maximum age of the desired document. |
KeepAlive | Determines whether the HTTP connection is closed after completion of the request. |
KerberosSPN | The Service Principal Name for the Kerberos Domain Controller. |
LogLevel | The level of detail that is logged. |
MaxRedirectAttempts | Limits the number of redirects that are followed in a request. |
NegotiatedHTTPVersion | The negotiated HTTP version. |
OtherHeaders | Other headers as determined by the user (optional). |
ProxyAuthorization | The authorization string to be sent to the proxy server. |
ProxyAuthScheme | The authorization scheme to be used for the proxy. |
ProxyPassword | A password if authentication is to be used for the proxy. |
ProxyPort | Port for the proxy server (default 80). |
ProxyServer | Name or IP address of a proxy server (optional). |
ProxyUser | A user name if authentication is to be used for the proxy. |
SentHeaders | The full set of headers as sent by the client. |
StatusLine | The first line of the last response from the server. |
TransferredData | The contents of the last response from the server. |
TransferredDataLimit | The maximum number of incoming bytes to be stored by the class. |
TransferredHeaders | The full set of headers as received from the server. |
TransferredRequest | The full request as sent by the client. |
UseChunkedEncoding | Enables or Disables HTTP chunked encoding for transfers. |
UseIDNs | Whether to encode hostnames to internationalized domain names. |
UsePlatformHTTPClient | Whether or not to use the platform HTTP client. |
UserAgent | Information about the user agent (browser). |
ConnectionTimeout | Sets a separate timeout value for establishing a connection. |
FirewallAutoDetect | Tells the class whether or not to automatically detect and use firewall system settings, if available. |
FirewallHost | Name or IP address of firewall (optional). |
FirewallPassword | Password to be used if authentication is to be used when connecting through the firewall. |
FirewallPort | The TCP port for the FirewallHost;. |
FirewallType | Determines the type of firewall to connect through. |
FirewallUser | A user name if authentication is to be used connecting through a firewall. |
KeepAliveInterval | The retry interval, in milliseconds, to be used when a TCP keep-alive packet is sent and no response is received. |
KeepAliveRetryCount | The number of keep-alive packets to be sent before the remotehost is considered disconnected. |
KeepAliveTime | The inactivity time in milliseconds before a TCP keep-alive packet is sent. |
Linger | When set to True, connections are terminated gracefully. |
LingerTime | Time in seconds to have the connection linger. |
LocalHost | The name of the local host through which connections are initiated or accepted. |
LocalPort | The port in the local host where the class binds. |
MaxLineLength | The maximum amount of data to accumulate when no EOL is found. |
MaxTransferRate | The transfer rate limit in bytes per second. |
ProxyExceptionsList | A semicolon separated list of hosts and IPs to bypass when using a proxy. |
TCPKeepAlive | Determines whether or not the keep alive socket option is enabled. |
TcpNoDelay | Whether or not to delay when sending packets. |
UseIPv6 | Whether to use IPv6. |
LogSSLPackets | Controls whether SSL packets are logged when using the internal security API. |
OpenSSLCADir | The path to a directory containing CA certificates. |
OpenSSLCAFile | Name of the file containing the list of CA's trusted by your application. |
OpenSSLCipherList | A string that controls the ciphers to be used by SSL. |
OpenSSLPrngSeedData | The data to seed the pseudo random number generator (PRNG). |
ReuseSSLSession | Determines if the SSL session is reused. |
SSLCACertFilePaths | The paths to CA certificate files on Unix/Linux. |
SSLCACerts | A newline separated list of CA certificate to use during SSL client authentication. |
SSLCipherStrength | The minimum cipher strength used for bulk encryption. |
SSLEnabledCipherSuites | The cipher suite to be used in an SSL negotiation. |
SSLEnabledProtocols | Used to enable/disable the supported security protocols. |
SSLEnableRenegotiation | Whether the renegotiation_info SSL extension is supported. |
SSLIncludeCertChain | Whether the entire certificate chain is included in the SSLServerAuthentication event. |
SSLNegotiatedCipher | Returns the negotiated ciphersuite. |
SSLNegotiatedCipherStrength | Returns the negotiated ciphersuite strength. |
SSLNegotiatedCipherSuite | Returns the negotiated ciphersuite. |
SSLNegotiatedKeyExchange | Returns the negotiated key exchange algorithm. |
SSLNegotiatedKeyExchangeStrength | Returns the negotiated key exchange algorithm strength. |
SSLNegotiatedVersion | Returns the negotiated protocol version. |
SSLProvider | The name of the security provider to use. |
SSLSecurityFlags | Flags that control certificate verification. |
SSLServerCACerts | A newline separated list of CA certificate to use during SSL server certificate validation. |
TLS12SignatureAlgorithms | Defines the allowed TLS 1.2 signature algorithms when UseInternalSecurityAPI is True. |
TLS12SupportedGroups | The supported groups for ECC. |
TLS13KeyShareGroups | The groups for which to pregenerate key shares. |
TLS13SignatureAlgorithms | The allowed certificate signature algorithms. |
TLS13SupportedGroups | The supported groups for (EC)DHE key exchange. |
AbsoluteTimeout | Determines whether timeouts are inactivity timeouts or absolute timeouts. |
FirewallData | Used to send extra data to the firewall. |
InBufferSize | The size in bytes of the incoming queue of the socket. |
OutBufferSize | The size in bytes of the outgoing queue of the socket. |