OpenID Class
Properties Methods Events Configuration Settings Errors
The OpenID class is used to verify the identify of a user as well as get basic profile information.
Syntax
ipworksauth.openid()
Remarks
The OpenID class implements an OpenID Connect 1.0 relying party (client) capable of authenticating a user and retrieving user information. OpenID Connect 1.0 is a simple identity layer on top of OAuth 2.0 and re-uses much of the functionality and concepts defined by OAuth 2.0.
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. The following sections discuss the typical steps to verify the identify of a user and obtain profile information.
Get the Discovery Document
Many OpenID providers provide information via a Discovery Document. The Discovery Document defines information such as the endpoint URLs for authentication, tokens, and user information requests. In addition details about the allowed parameters such as supported authorization scopes are defined in this document. The document at a URL which can be fetched and parsed by calling the GetDiscoveryDoc method.
The discovery document URL is typically published by an OpenID provider and must be known before calling this method. The format of the URL is standardized and typically takes the form:
https://www.youropenidserver.com/.well-known/openid-configuration
Call GetDiscoveryDoc before calling GetAuthorization to populate the class properties with information required to complete the authorization. The retrieved information includes endpoint URLs as well as the OpenID public certificates used to verify the signature on the ID token. After calling this method the following properties are populated:
The above values may be stored, and later populated from the stored values, to avoid the requirement of calling GetDiscoveryDoc on subsequent authorization requests.
The following discovery document fields are populated after GetDiscoveryDoc returns:
- DiscoveryDocDetailsAuthorizationURL
- DiscoveryDocDetailsClaimsParamSupported
- DiscoveryDocDetailsIssuer
- DiscoveryDocDetailsSignerCertURL
- DiscoveryDocDetailsRegistrationURL
- DiscoveryDocDetailsServiceDocsURL
- DiscoveryDocDetailsSupportedClaims
- DiscoveryDocDetailsSupportedDisplays
- DiscoveryDocDetailsSupportedGrantTypes
- DiscoveryDocDetailsSupportedResponseTypes
- DiscoveryDocDetailsSupportedScopes
- DiscoveryDocDetailsTokenURL
- DiscoveryDocDetailsUserInfoURL
To access values not automatically parsed by the class the XPath configuration setting may be set to retrieve a specific value. Alternatively the RawJSON setting returns the entire JSON document which may be parsed separately.
Note: Calling GetDiscoveryDoc is not mandatory. If server information was stored from a previous call or is otherwise known ahead of time the following properties may be set in place of calling GetDiscoveryDoc:
Examples of the above points:
openid.GetDiscoveryDoc(
"https://accounts.google.com/.well-known/openid-configuration"
);
// ... or ...
openid.ServerAuthURL =
"https://accounts.google.com/o/oauth2/v2/auth"
;
openid.ServerTokenURL =
"https://oauth2.googleapis.com/token"
;
openid.ServerUserInfoURL =
"https://openidconnect.googleapis.com/v1/userinfo"
;
openid.SignerCertURL =
"https://www.googleapis.com/oauth2/v3/certs"
;
// ... or ...
string
rawjson = openid.Config(
"RawJSON"
);
Get Authorization
Before calling GetAuthorization the class may be configured for one of several flows defined by the GrantType property. These flows determine which information is returned by the authorization server and which information (if any) is returned by the token server.
Possible values for GrantType are:
- 0 (Authorization Code - Default)
- 1 (Implicit)
- 2 (Hybrid)
When using 0 (Authorization Code Flow - Default) an authorization code is returned from the ServerAuthURL and the class automatically contacts the ServerTokenURL exchanges the authorization code for an ID token and access token.
When using 1 (Implicit Flow) the ServerAuthURL returns an ID token and access token directly. This is only recommended for implementations that are in-browser as this potentially exposes the tokens to the end-user and user agent itself.
When using 2 (Hybrid Flow) an authorization code and potentially one or more tokens are returned by the ServerAuthURL. The class will automatically contact the ServerTokenURL to exchange the authorization code for an ID token and access token.
When GrantType and any other optional settings are set as desired, call GetAuthorization.
GetAuthorization performs several operations automatically depending on the value of ClientProfile. Please see the introduction section for the OpenID class for a detailed overview of the typical scenarios.
After authorization is complete UserDetails will be populated with the claims parsed from the ID token. This method also returns an authorization string. The authorization string grants access to additional resources as requested via the AuthorizationScope property. If access to another resource was requested the access token returned here may be set in the Authorization property of any other class (or passed as the value of the HTTP Authorization header).
GetUserInfo may be called after calling this method.
The following properties are applicable when calling this method:
- ClientId (required)
- ClientSecret (required)
- ServerAuthURL (required - populated by GetDiscoveryDoc.)
- ServerTokenURL (required - populated by GetDiscoveryDoc.)
- SignerCertURL (conditional - populated by GetDiscoveryDoc. Required if SignerCert is not set.)
- SignerCert (conditional - required if SignerCertURL is not set.)
- AuthorizationScope
- ClientProfile
- GrantType
- Params
- RefreshToken
- ReturnURL
- State
- Timeout
- Display
- Prompt
- IDTokenHint
- LoginHint
- ResponseType
For the default Authorization Code flow GetAuthorization could work like this:
openid.ClientId =
"client id"
;
openid.ClientSecret =
"client secret"
;
openid.AuthorizationScope +=
" profile email"
;
// default value is 'openid'
openid.State =
"application state"
;
string
authToken = openid.GetAuthorization();
Get User Info
When GetAuthorization returns the UserDetails property is populated with information about the user as returned in the ID token from the authorization server. An additional operation, GetUserInfo may optionally be called to query the ServerUserInfoURL for information about the user.
Before calling GetUserInfo method a successful call to GetAuthorization must be made. The access token returned by GetAuthorization is used by the OpenID provider at ServerUserInfoURL to identify the user for which claims are being retrieved.
When this method is called the class requests the claims about the user from the ServerUserInfoURL. The resulting claims are available in the UserDetail* properties.
Note: The GetUserInfo method will populate the UserDetail* properties with the claims returned in the ID token during the authorization process. This method may not need to be called in order to access the desired claims about the user.
openid.GetUserInfo();
// ... use the user info in the remainder of your application ...
Client Profile Notes
The ClientProfile defines the environment in which the class is being used, and controls how the class behaves in order to best suit that environment. Choose the profile that is closest to the runtime environment.
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.
For additional details for less common profile types please see ClientProfile.
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 authorization scope 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. |
Cookies | Collection of cookies. |
DiscoveryDocDetails | Details about the OpenID provider's discovery document. |
Firewall | A set of properties related to firewall access. |
FollowRedirects | Determines what happens when the server issues a redirect. |
GrantType | The grant type defining the authentication flow. |
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). |
Params | The parameters to be included in the request to the authorization server, or received in the response. |
Proxy | A set of properties related to proxy access. |
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. |
ServerUserInfoURL | The URL of the OpenID provider's user info endpoint. |
SignerCert | The JWT public signer certificate. |
SignerCertURL | The URL of the OpenID provider's signing certificate. |
SSLAcceptServerCert | Instructs the class to unconditionally accept the server certificate that matches the supplied certificate. |
SSLCert | The certificate to be used during SSL negotiation. |
SSLServerCert | The server certificate for the last established connection. |
State | Opaque value used to maintain state between the request and response. |
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. |
UserDetails | The claims about the user. |
WebServerPort | The local port on which the embedded web server listens. |
WebServerSSLCert | The certificate with private key to use when SSL is enabled. |
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. |
GetDiscoveryDoc | Gets the OpenID Discovery Document. |
GetUserInfo | Retrieves claims about the user. |
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.
Display | The requested display options to present to the end user. |
IDToken | The raw ID token returned after authorization. |
IDTokenHint | An ID token value to be used as a hint about the user's session. |
LoginHint | The login hint sent to the authorization server. |
Prompt | The requested conditions under which the authorization server prompts for login. |
RawJSON | A JSON string holding the last response. |
ResponseType | The value of the response_type request parameter. |
XChildCount | The number of child elements of the current element. |
XChildName[i] | The name of the child element. |
XChildXText[i] | The inner text of the child element. |
XElement | The name of the current element. |
XParent | The parent of the current element. |
XPath | Provides a way to point to a specific element in the returned XML or JSON response. |
XSubTree | A snapshot of the current element in the document. |
XText | The text of the current element. |
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. |
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. |
Username | The Username field when using the password grant type. |
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. |
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. |
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. |
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. |
BuildInfo | Information about the product's build. |
CodePage | The system code page used for Unicode to Multibyte translations. |
LicenseInfo | Information about the current license. |
UseInternalSecurityAPI | Tells the class whether or not to use the system security libraries or an internal implementation. |