IPWorks Auth 2020 Python Edition

Questions / Feedback?

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

class 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 client_id and client_secret. 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 get_discovery_doc 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 get_discovery_doc before calling get_authorization 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 get_discovery_doc on subsequent authorization requests.

The following discovery document fields are populated after get_discovery_doc returns:

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 get_discovery_doc 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 get_discovery_doc:

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 get_authorization the class may be configured for one of several flows defined by the grant_type 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 grant_type are:

  • 0 (Authorization Code - Default)
  • 1 (Implicit)
  • 2 (Hybrid)

When using 0 (Authorization Code Flow - Default) an authorization code is returned from the server_auth_url and the class automatically contacts the server_token_url exchanges the authorization code for an ID token and access token.

When using 1 (Implicit Flow) the server_auth_url 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 server_auth_url. The class will automatically contact the server_token_url to exchange the authorization code for an ID token and access token.

When grant_type and any other optional settings are set as desired, call get_authorization.

get_authorization performs several operations automatically depending on the value of client_profile. Please see the introduction section for the OpenID class for a detailed overview of the typical scenarios.

After authorization is complete user_details 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 authorization_scope 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).

get_user_info may be called after calling this method.

The following properties are applicable when calling this method:

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 get_authorization returns the user_details property is populated with information about the user as returned in the ID token from the authorization server. An additional operation, get_user_info may optionally be called to query the server_user_info_url for information about the user.

Before calling get_user_info method a successful call to get_authorization must be made. The access token returned by get_authorization is used by the OpenID provider at server_user_info_url 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 server_user_info_url. The resulting claims are available in the UserDetail* properties.

Note: The get_user_info 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 client_profile 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 client_profile to cfApplication. This defines the client type the class will use. Set the client_id, client_secret, server_auth_url, and server_token_url to the values you obtained when registering your application.

Next, call get_authorization to begin the authorization process. When get_authorization is called the class will build the URL to which the user will be directed and fire the on_launch_browser event. The class will then launch the browser using the command and URL shown in the on_launch_browser event.

The user will authenticate to the service, and then be redirected back to an embedded web server that was automatically started when get_authorization was called. At this time the on_return_url 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 server_token_url.

The authorization is now complete and the get_authorization 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 client_profile to cfWebServer. This defines the client type the component will use. Set the client_id, client_secret, server_auth_url, and server_token_url to the values you obtained when registering your application. Set return_url to the page on your site that will be the endpoint the user is redirected back to after authentication.

Next, call get_authorization_url. 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 return_url, parse the "code" query string parameter from the incoming request. Set authorization_code to this value.

Call get_authorization to exchange the code specified in authorization_code for a token from the server specified by server_token_url. get_authorization 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 client_profile.

Property List


The following is the full list of the properties of the class with short descriptions. Click on the links for further details.

access_tokenThe access token returned by the authorization server.
authorization_codeThe authorization code that is exchanged for an access token.
authorization_scopeThe authorization scope used during authorization.
client_idThe id of the client assigned when registering the application.
client_profileThe type of client that is requesting authorization.
client_secretThe secret value for the client assigned when registering the application.
connectedShows whether the class is connected.
cookie_countThe number of records in the Cookie arrays.
cookie_domainThe domain of a received cookie.
cookie_expirationThis property contains an expiration time for the cookie (if provided by the server).
cookie_nameThe name of the cookie.
cookie_pathThis property contains a path name to limit the cookie to (if provided by the server).
cookie_secureThis property contains the security flag of the received cookie.
cookie_valueThis property contains the value of the cookie.
discovery_doc_details_authorization_urlThis property holds the server authorization endpoint URL.
discovery_doc_details_claims_param_supportedThis property indicates whether the claims request parameter is supported by the Open ID provider.
discovery_doc_details_issuerThis property holds the issuer identifier of the OpenID provider.
discovery_doc_details_registration_urlThis property holds the dynamic client registration URL.
discovery_doc_details_service_docs_urlThis property contains the URL of the human-readable service documentation.
discovery_doc_details_signer_cert_urlThis property holds the URL of the JSON Web Key Set used to verify signatures on values returned by the OpenID provider.
discovery_doc_details_supported_claimsThis property holds a comma separated list of claims that are supported by the OpenID provider.
discovery_doc_details_supported_displaysThis property holds a comma separated list of display values that are supported by the OpenID provider.
discovery_doc_details_supported_grant_typesThis property holds a comma separated list of grant types supported by the OpenID provider.
discovery_doc_details_supported_response_typesThis property hold a comma separated list of response types supported by the OpenID provider.
discovery_doc_details_supported_scopesThis property hold a comma separated list of scopes that are supported by the OpenID provider.
discovery_doc_details_token_urlThis property holds the token endpoint URL.
discovery_doc_details_user_info_urlThis property holds the user info endpoint URL.
firewall_auto_detectThis property tells the class whether or not to automatically detect and use firewall system settings, if available.
firewall_typeThis property determines the type of firewall to connect through.
firewall_hostThis property contains the name or IP address of firewall (optional).
firewall_passwordThis property contains a password if authentication is to be used when connecting through the firewall.
firewall_portThis property contains the TCP port for the firewall Host .
firewall_userThis property contains a user name if authentication is to be used connecting through a firewall.
follow_redirectsDetermines what happens when the server issues a redirect.
grant_typeThe grant type defining the authentication flow.
idleThe current status of the class.
local_hostThe name of the local host or user-assigned IP interface through which connections are initiated or accepted.
other_headersOther headers as determined by the user (optional).
param_countThe number of records in the Param arrays.
param_nameThis property contains the name of the parameter to be used in the request or returned in the response.
param_valueThis property contains the value of the parameter to be used in the request or returned in the response.
proxy_auth_schemeThis property is used to tell the class which type of authorization to perform when connecting to the proxy.
proxy_auto_detectThis property tells the class whether or not to automatically detect and use proxy system settings, if available.
proxy_passwordThis property contains a password if authentication is to be used for the proxy.
proxy_portThis property contains the TCP port for the proxy Server (default 80).
proxy_serverIf a proxy Server is given, then the HTTP request is sent to the proxy instead of the server otherwise specified.
proxy_sslThis property determines when to use SSL for the connection to the proxy.
proxy_userThis property contains a user name, if authentication is to be used for the proxy.
refresh_tokenSpecifies the refresh token received from or sent to the authorization server.
return_urlThe URL where the user (browser) returns after authenticating.
server_auth_urlThe URL of the authorization server.
server_token_urlThe URL used to obtain the access token.
server_user_info_urlThe URL of the OpenID provider's user info endpoint.
signer_cert_encodedThe certificate (PEM/base64 encoded).
signer_cert_storeThe name of the certificate store for the client certificate.
signer_cert_store_passwordIf 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.
signer_cert_store_typeThe type of certificate store for this certificate.
signer_cert_subjectThe subject of the certificate used for client authentication.
signer_cert_urlThe URL of the OpenID provider's signing certificate.
ssl_accept_server_cert_encodedThe certificate (PEM/base64 encoded).
ssl_cert_encodedThe certificate (PEM/base64 encoded).
ssl_cert_storeThe name of the certificate store for the client certificate.
ssl_cert_store_passwordIf 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.
ssl_cert_store_typeThe type of certificate store for this certificate.
ssl_cert_subjectThe subject of the certificate used for client authentication.
ssl_server_cert_encodedThe certificate (PEM/base64 encoded).
stateOpaque value used to maintain state between the request and response.
timeoutA timeout for the class.
transferred_dataThe contents of the last response from the server.
transferred_headersThe full set of headers as received from the server.
user_details_addr_countryThis property holds the country name portion of the user's address.
user_details_addr_formattedThis property holds the full mailing address of the user, formatted for display or use on a mailing label.
user_details_addr_localityThis property holds the city or locality portion of the user's address.
user_details_addr_postal_codeThis property holds the zip code or postal code portion of the user's address.
user_details_addr_regionThis property holds the state, province, prefecture, or region portion of the user's address.
user_details_addr_street_addrThis property holds the street address portion of the user's address.
user_details_audiencesThis property contains a comma separated list of audiences for which the user information is intended.
user_details_birthdayThis property contains the user's birthday.
user_details_emailThis property contains the user's preferred email address.
user_details_email_verifiedThis property indicates whether the user's email address has been verified.
user_details_first_nameThis property holds the first name of the user.
user_details_genderThis property holds the user's gender.
user_details_issuerThis property contains the identifier of the issuer who issued the ID token.
user_details_last_nameThis property holds the last name of the user.
user_details_localeThis property holds the end user's locale.
user_details_middle_nameThis property holds the middle name of the user.
user_details_nameThis property contains the user's full name in displayable form including all name parts.
user_details_nicknameThis property holds the casual name of the user.
user_details_phone_numberThis property holds the user's phone number.
user_details_phone_number_verifiedThis property indicates whether the user's phone number has been verified.
user_details_picture_urlThis property holds the URL of the user's profile picture.
user_details_preferred_usernameThis property holds the shorthand name by which the end-user wishes to be referred.
user_details_profile_urlThis property holds the URL of the user's profile page.
user_details_subjectThis property holds the subject identifier of the token.
user_details_token_auth_timeThis property holds the time when authentication occurred.
user_details_token_exp_timeThis property holds the expiration time of the token.
user_details_token_issued_atThis property holds the time when the token was issued.
user_details_updated_atThis property holds the time when the user's information was last updated.
user_details_websiteThis property holds the URL of the user's website.
user_details_zone_infoThis property holds the user's time zone.
web_server_portThe local port on which the embedded web server listens.
web_server_ssl_cert_storeThe name of the certificate store for the client certificate.
web_server_ssl_cert_store_passwordIf 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.
web_server_ssl_cert_store_typeThe type of certificate store for this certificate.
web_server_ssl_cert_subjectThe subject of the certificate used for client authentication.
web_server_ssl_enabledWhether 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.

add_cookieAdds a cookie and the corresponding value to the outgoing request headers.
add_paramAdds a name-value pair to the query string parameters of outgoing request.
configSets or retrieves a configuration setting.
do_eventsProcesses events from the internal message queue.
get_authorizationGets the authorization string required to access the protected resource.
get_authorization_urlBuilds and returns the URL to which the user should be re-directed for authorization.
get_discovery_docGets the OpenID Discovery Document.
get_user_infoRetrieves claims about the user.
interruptInterrupt the current method.
resetReset the class.
start_web_serverStarts the embedded web server.
stop_web_serverStops 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.

on_connectedFired immediately after a connection completes (or fails).
on_connection_statusFired to indicate changes in connection state.
on_disconnectedFired when a connection is closed.
on_end_transferFired when a document finishes transferring.
on_errorInformation about errors during data delivery.
on_headerFired every time a header line comes in.
on_launch_browserFires before launching a browser with the authorization URL.
on_logFires once for each log message.
on_redirectFired when a redirection is received from the server.
on_return_urlFires when the user is redirected to the embedded web server.
on_set_cookieFired for every cookie set by the server.
on_ssl_server_authenticationFired after the server presents its certificate to the client.
on_ssl_statusShows the progress of the secure connection.
on_start_transferFired when a document starts transferring (after the headers).
on_statusFired when the HTTP status line is received from the server.
on_transferFired 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.

DisplayThe requested display options to present to the end user.
IDTokenThe raw ID token returned after authorization.
IDTokenHintAn ID token value to be used as a hint about the user's session.
LoginHintThe login hint sent to the authorization server.
PromptThe requested conditions under which the authorization server prompts for login.
RawJSONA JSON string holding the last response.
ResponseTypeThe value of the response_type request parameter.
XChildCountThe 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.
XElementThe name of the current element.
XParentThe parent of the current element.
XPathProvides a way to point to a specific element in the returned XML or JSON response.
XSubTreeA snapshot of the current element in the document.
XTextThe text of the current element.
AccessTokenExpThe lifetime of the access token.
AuthorizationTokenTypeThe type of access token returned.
AuthorizationURLSpecifies the URL used for authorization.
BrowserResponseTimeoutSpecifies the amount of time to wait for a response from the browser.
CodeChallengeMethodThe code challenge method to use (if any).
DeviceGrantTypeThe grant type to be used when the ClientProfile is set to cfDevice.
DeviceUserCodeThe device's user code when the ClientProfile is set to cfDevice.
FormVarCountSpecifies 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.
IncludeEmptyRedirectURIWhether an empty redirect_uri parameter is included in requests.
JWTAudienceThe JWT audience when the ClientProfile is set to cfJWT.
JWTCertStoreThe name of the certificate store for the JWT signing certificate.
JWTCertStorePasswordThe JWT signing certificate password.
JWTCertStoreTypeThe type of certificate store.
JWTCertSubjectThe JWT signing certificate subject.
JWTIssuerThe JWT issuer when the ClientProfile is set to cfJWT.
JWTJSONKeyThe file path of the JWT JSON Key, or a string containing its content.
JWTServiceProviderThe service provider to which authentication is being performed.
JWTSignatureAlgorithmThe signature algorithm used to sign the JWT.
JWTSubjectThe subject field in the JWT.
JWTValidityTimeThe amount of time in seconds for which the assertion in the JWT is valid.
Microsoft365AdminConsentErrorThe error message returned when the admin denies consent to the scopes.
Microsoft365AdminConsentErrorDescThe error description returned when the admin denies consent to the scopes.
Microsoft365AdminConsentTenantThe tenant ID returned after the admin consents to the scopes.
Office365ServiceAPIVersionThe API version of the Office 365 service being discovered.
Office365ServiceCapabilityThe API capability of the Office 365 service being discovered.
Office365ServiceEndpointThe Office 365 endpoint for the service that matches the criteria specified.
PollingIntervalThe interval in seconds between polling requests when the device client type is used.
ReUseWebServerDetermines if the same server instance is used between requests.
TokenInfoFieldCountThe 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.
TokenInfoURLThe URL of the tokeninfo service.
ValidateTokenValidates the specified access token with a tokeninfo service.
WebServerFailedResponseThe custom response that will be displayed to the user if authentication failed.
WebServerHostThe hostname used by the embedded web server displayed in the ReturnURL.
WebServerResponseThe custom response that will be displayed to the user.
AcceptEncodingUsed to tell the server which types of content encodings the client supports.
AllowHTTPCompressionThis property enables HTTP compression for receiving data.
AllowHTTPFallbackWhether HTTP/2 connections are permitted to fallback to HTTP/1.1.
AppendWhether to append data to LocalFile.
AuthorizationThe Authorization string to be sent to the server.
BytesTransferredContains the number of bytes transferred in the response data.
ChunkSizeSpecifies the chunk size in bytes when using chunked encoding.
CompressHTTPRequestSet to true to compress the body of a PUT or POST request.
EncodeURLIf set to true the URL will be encoded by the class.
FollowRedirectsDetermines what happens when the server issues a redirect.
GetOn302RedirectIf set to true the class will perform a GET on the new location.
HTTP2HeadersWithoutIndexingHTTP2 headers that should not update the dynamic header table with incremental indexing.
HTTPVersionThe version of HTTP used by the class.
IfModifiedSinceA date determining the maximum age of the desired document.
KeepAliveDetermines whether the HTTP connection is closed after completion of the request.
KerberosSPNThe Service Principal Name for the Kerberos Domain Controller.
LogLevelThe level of detail that is logged.
MaxRedirectAttemptsLimits the number of redirects that are followed in a request.
NegotiatedHTTPVersionThe negotiated HTTP version.
OtherHeadersOther headers as determined by the user (optional).
ProxyAuthorizationThe authorization string to be sent to the proxy server.
ProxyAuthSchemeThe authorization scheme to be used for the proxy.
ProxyPasswordA password if authentication is to be used for the proxy.
ProxyPortPort for the proxy server (default 80).
ProxyServerName or IP address of a proxy server (optional).
ProxyUserA user name if authentication is to be used for the proxy.
SentHeadersThe full set of headers as sent by the client.
StatusLineThe first line of the last response from the server.
TransferredDataThe contents of the last response from the server.
TransferredDataLimitThe maximum number of incoming bytes to be stored by the class.
TransferredHeadersThe full set of headers as received from the server.
TransferredRequestThe full request as sent by the client.
UseChunkedEncodingEnables or Disables HTTP chunked encoding for transfers.
UseIDNsWhether to encode hostnames to internationalized domain names.
UsePlatformHTTPClientWhether or not to use the platform HTTP client.
UserAgentInformation about the user agent (browser).
ConnectionTimeoutSets a separate timeout value for establishing a connection.
FirewallAutoDetectTells the class whether or not to automatically detect and use firewall system settings, if available.
FirewallHostName or IP address of firewall (optional).
FirewallPasswordPassword to be used if authentication is to be used when connecting through the firewall.
FirewallPortThe TCP port for the FirewallHost;.
FirewallTypeDetermines the type of firewall to connect through.
FirewallUserA user name if authentication is to be used connecting through a firewall.
KeepAliveIntervalThe retry interval, in milliseconds, to be used when a TCP keep-alive packet is sent and no response is received.
KeepAliveTimeThe inactivity time in milliseconds before a TCP keep-alive packet is sent.
LingerWhen set to True, connections are terminated gracefully.
LingerTimeTime in seconds to have the connection linger.
LocalHostThe name of the local host through which connections are initiated or accepted.
LocalPortThe port in the local host where the class binds.
MaxLineLengthThe maximum amount of data to accumulate when no EOL is found.
MaxTransferRateThe transfer rate limit in bytes per second.
ProxyExceptionsListA semicolon separated list of hosts and IPs to bypass when using a proxy.
TCPKeepAliveDetermines whether or not the keep alive socket option is enabled.
TcpNoDelayWhether or not to delay when sending packets.
UseIPv6Whether to use IPv6.
AbsoluteTimeoutDetermines whether timeouts are inactivity timeouts or absolute timeouts.
FirewallDataUsed to send extra data to the firewall.
InBufferSizeThe size in bytes of the incoming queue of the socket.
OutBufferSizeThe size in bytes of the outgoing queue of the socket.
BuildInfoInformation about the product's build.
CodePageThe system code page used for Unicode to Multibyte translations.
LicenseInfoInformation about the current license.
ProcessIdleEventsWhether the class uses its internal event loop to process events when the main thread is idle.
SelectWaitMillisThe length of time in milliseconds the class will wait when DoEvents is called if there are no events to process.
UseInternalSecurityAPITells the class whether or not to use the system security libraries or an internal implementation.

Copyright (c) 2022 /n software inc. - All rights reserved.
IPWorks Auth 2020 Python Edition - Version 20.0 [Build 8155]