Chilkat HOME .NET Core C# Android™ AutoIt C C# C++ Chilkat2-Python CkPython Classic ASP DataFlex Delphi ActiveX Delphi DLL Go Java Lianja Mono C# Node.js Objective-C PHP ActiveX PHP Extension Perl PowerBuilder PowerShell PureBasic Ruby SQL Server Swift 2 Swift 3,4,5... Tcl Unicode C Unicode C++ VB.NET VBScript Visual Basic 6.0 Visual FoxPro Xojo Plugin
(CkPython) Uni Economy API Client Credentials FlowDemonstrates how to do OAuth 2.0 using the client credentials flow for the Uni Economy API. (This means that the server can authenticate against the identity server without human interaction.) For more information, see https://developer.unieconomy.no/wiki/introduction/getting-started/server-application
import sys import chilkat # This example requires the Chilkat API to have been previously unlocked. # See Global Unlock Sample for sample code. # Step 1 ------------------------------------------------------------------------------------------ # First create a client token... cert = chilkat.CkCert() cert.put_VerboseLogging(True) # Note: .pfx and .p12 files are identical. The only difference is the file extension. # Also, if your .p12 password is longer than 64 chars, you'll need Chilkat v9.5.0.83 or later. # To shorten the password, import your .p12 onto your Windows computer by double-clicking on the .p12 file, # make sure when importing that keys are exportable, then re-export with private keys to a .pfx with a new password. success = cert.LoadPfxFile("qa_data/pfx/UniCert_Norge_Test_secret.pfx","secret") if (success == False): print(cert.lastErrorText()) sys.exit() # privKey is a CkPrivateKey privKey = cert.ExportPrivateKey() if (cert.get_LastMethodSuccess() == False): print(cert.lastErrorText()) sys.exit() jwt = chilkat.CkJwt() # Build the JOSE header jose = chilkat.CkJsonObject() # Use RS256. Pass the string "RS384" or "RS512" to use RSA with SHA-384 or SHA-512. success = jose.AppendString("alg","RS256") success = jose.AppendString("typ","JWT") # Now build the JWT claims (also known as the payload) # Our JWT claims will contain members as shown here: # { # "jti": "ad612fce-3e71-4f6a-8af1-7eb0414b4eea", <-- generated unique global identifier # "sub": "99999999-aaaa-bbbb-cccc-ddddeeeeffff", <-- This is the clientId # "iat": 1588102982, <-- These are date/time values. # "nbf": 1588102982, # "exp": 1588103042, # "iss": " 99999999-aaaa-bbbb-cccc-ddddeeeeffff", # "aud": "https://test-login.unieconomy.no/connect/token" # } # Use your own client ID. myClientId = "99999999-aaaa-bbbb-cccc-ddddeeeeffff" claims = chilkat.CkJsonObject() crypt = chilkat.CkCrypt2() claims.AppendString("jti",crypt.generateUuid()) claims.AppendString("sub",myClientId) # Set the timestamp of when the JWT was created to now minus 60 seconds curDateTime = jwt.GenNumericDate(-60) success = claims.AddIntAt(-1,"iat",curDateTime) # Set the "not process before" timestamp to now minus 60 seconds success = claims.AddIntAt(-1,"nbf",curDateTime) # Set the timestamp defining an expiration time (end time) for the token # to be now + 1 hour (3600 seconds) success = claims.AddIntAt(-1,"exp",curDateTime + 3600) claims.AppendString("iss",myClientId) claims.AppendString("aud","https://test-login.unieconomy.no/connect/token") # Produce the smallest possible JWT: jwt.put_AutoCompact(True) # Create the JWT token. This is where the RSA signature is created. jwt_token = jwt.createJwtPk(jose.emit(),claims.emit(),privKey) print(jwt_token) # Step 2 ------------------------------------------------------------------------------------------ http = chilkat.CkHttp() # Fetch the discovery document... # resp is a CkHttpResponse resp = http.QuickRequest("GET","https://test-login.unieconomy.no/.well-known/openid-configuration") if (http.get_LastMethodSuccess() != True): print(http.lastErrorText()) sys.exit() if (resp.get_StatusCode() != 200): print("Received response status code " + str(resp.get_StatusCode())) print("Response body containing error text or JSON:") print(resp.bodyStr()) sys.exit() json = chilkat.CkJsonObject() success = json.Load(resp.bodyStr()) json.put_EmitCompact(False) print(json.emit()) # We have the discovery document, which contains something like this: # You can use this online tool to generate parsing code from sample JSON: # Generate Parsing Code from JSON # { # "issuer": "https://test-login.unieconomy.no", # "jwks_uri": "https://test-login.unieconomy.no/.well-known/openid-configuration/jwks", # "authorization_endpoint": "https://test-login.unieconomy.no/connect/authorize", # "token_endpoint": "https://test-login.unieconomy.no/connect/token", # "userinfo_endpoint": "https://test-login.unieconomy.no/connect/userinfo", # "end_session_endpoint": "https://test-login.unieconomy.no/connect/endsession", # "check_session_iframe": "https://test-login.unieconomy.no/connect/checksession", # "revocation_endpoint": "https://test-login.unieconomy.no/connect/revocation", # "introspection_endpoint": "https://test-login.unieconomy.no/connect/introspect", # "device_authorization_endpoint": "https://test-login.unieconomy.no/connect/deviceauthorization", # "frontchannel_logout_supported": true, # "frontchannel_logout_session_supported": true, # "backchannel_logout_supported": true, # "backchannel_logout_session_supported": true, # "scopes_supported": [ # "openid", # "profile", # "email", # "offline_access", # "AppFramework.All", # "AppFramework", # "AppFramework.Sales", # "IdentityAPI", # "widgetApi", # "TestScope.test", # "TestScope.Cars", # "HaglandAPI", # "LicenseAdmin", # "LicenseAdmin.Product.Read", # "SoftRig.Product.Write", # "TestAPI.test", # "offline_access" # ], # "claims_supported": [ # "sub", # "updated_at", # "name", # "family_name", # "given_name", # "middle_name", # "nickname", # "preferred_username", # "picture", # "website", # "gender", # "birthdate", # "zoneinfo", # "locale", # "profile", # "email", # "email_verified" # ], # "grant_types_supported": [ # "authorization_code", # "client_credentials", # "refresh_token", # "implicit", # "password", # "urn:ietf:params:oauth:grant-type:device_code", # "delegation" # ], # "response_types_supported": [ # "code", # "token", # "id_token", # "id_token token", # "code id_token", # "code token", # "code id_token token" # ], # "response_modes_supported": [ # "form_post", # "query", # "fragment" # ], # "token_endpoint_auth_methods_supported": [ # "client_secret_basic", # "client_secret_post", # "private_key_jwt", # "private_key_jwt" # ], # "id_token_signing_alg_values_supported": [ # "RS256" # ], # "subject_types_supported": [ # "public" # ], # "code_challenge_methods_supported": [ # "plain", # "S256" # ], # "request_parameter_supported": true # } # ------------------------------------------------------ # The next steps are to (1) get the token_endpoint, # and (2) verify that the client_credentials grant type is supported. tokenEndpoint = json.stringOf("token_endpoint") # grantTypes is a CkJsonArray grantTypes = json.ArrayOf("grant_types_supported") clientCredentialsIdx = grantTypes.FindString("client_credentials",True) # If clientCredentialsIdx is less then zero (-1) then the "client_credentials" string was not found. if (clientCredentialsIdx < 0): print("The client credentials grant type is not supported.") sys.exit() # ------------------------------------------------------ # Request the access token using our Client ID and JWT req = chilkat.CkHttpRequest() req.put_HttpVerb("POST") req.AddParam("client_id",myClientId) req.AddParam("scope","AppFramework.Sales") req.AddParam("grant_type","client_credentials") req.AddParam("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer") req.AddParam("client_assertion",jwt_token) # resp is a CkHttpResponse resp = http.PostUrlEncoded(tokenEndpoint,req) if (http.get_LastMethodSuccess() == False): print(http.lastErrorText()) sys.exit() # Make sure we got a 200 response status code, otherwise it's an error. if (resp.get_StatusCode() != 200): print("POST to token endpoint failed.") print("Received response status code " + str(resp.get_StatusCode())) print("Response body containing error text or JSON:") print(resp.bodyStr()) sys.exit() success = json.Load(resp.bodyStr()) print(json.emit()) # The JSON response will look like this: # { # "access_token": "...", # "expires_in": 3600, # "token_type": "Bearer", # "scope": "AppFramework.Sales" # } # Get the access token: accessToken = json.stringOf("access_token") print("accessToken = " + accessToken) # ------------------------------------------------------ # Use the access token in a request. # We'll just send a GET request to https://test.unieconomy.no/api/init/companies # Tell the http object to use the OAuth2 access token in the "Authorization: Bearer ..." header. http.put_AuthToken(accessToken) sbResponse = chilkat.CkStringBuilder() success = http.QuickGetSb("https://test.unieconomy.no/api/init/companies",sbResponse) if (success == False): print(http.lastErrorText()) sys.exit() # Examine the response status code. if (http.get_LastStatus() != 200): print(sbResponse.getAsString()) print("response status: " + str(http.get_LastStatus())) print("Received error response.") sys.exit() json.LoadSb(sbResponse) print(json.emit()) print("Success.") |
© 2000-2024 Chilkat Software, Inc. All Rights Reserved.