Chilkat HOME Android™ Classic ASP C C++ C# Mono C# .NET Core C# C# UWP/WinRT DataFlex Delphi ActiveX Delphi DLL Visual FoxPro Java Lianja MFC Objective-C Perl PHP ActiveX PHP Extension PowerBuilder PowerShell PureBasic CkPython Chilkat2-Python Ruby SQL Server Swift 2 Swift 3,4,5... Tcl Unicode C Unicode C++ Visual Basic 6.0 VB.NET VB.NET UWP/WinRT VBScript Xojo Plugin Node.js Excel Go
(Excel) Box.com OAuth2 with JSON Web TokensDemonstrates how to obtain an OAuth2 access token using a JSON Web Token. The following explanation is copied from Box Authentication Models
' This requires the Chilkat API to have been previously unlocked. ' See Global Unlock Sample for sample code. ' When you created an RSA key pair using the Box web user interface, ' you downloaded a json file named something like "7152782_kkdxptq2_config.json" ' This contains the following: ' { ' "boxAppSettings": { ' "clientID": "0kraci84o0jfr7yuw596tf394iigzbe7", ' "clientSecret": "xxxxxxxxxxxxxxxxxxxxxxxxx", ' "appAuth": { ' "publicKeyID": "kkdxptq2", ' "privateKey": "-----BEGIN ENCRYPTED PRIVATE KEY-----\nMIIFDj ... nceU=\n-----END ENCRYPTED PRIVATE KEY-----\n", ' "passphrase": "xxxxxxxxxxxxxxxxxxxxxxxx" ' } ' }, ' "enterpriseID": "7152782" ' } ' ' Load it into a Chilkat JSON object to allow access to the content. Dim jsonRsaKey As Chilkat.JsonObject Set jsonRsaKey = Chilkat.NewJsonObject success = jsonRsaKey.LoadFile("qa_data/tokens/7152782_kkdxptq2_config.json") ' Load the private key into a Chilkat private key object. passphrase = jsonRsaKey.StringOf("boxAppSettings.appAuth.passphrase") privateKeyPem = jsonRsaKey.StringOf("boxAppSettings.appAuth.privateKey") Dim rsaKey As Chilkat.PrivateKey Set rsaKey = Chilkat.NewPrivateKey success = rsaKey.LoadEncryptedPem(privateKeyPem,passphrase) If (success <> True) Then Debug.Print rsaKey.LastErrorText Exit Sub End If ' The JSON Web Token will be created using the JWT class Dim jwt As Chilkat.Jwt Set jwt = Chilkat.NewJwt ' Construct the JOSE header... Dim jose As Chilkat.JsonObject Set jose = Chilkat.NewJsonObject ' Chilkat supports the following algorithms: "RS256", "RS384", and "RS512". (Chilkat also supports other algorithms that Box does not yet support.) success = jose.UpdateString("alg","RS256") success = jose.UpdateString("typ","JWT") success = jose.UpdateString("kid",jsonRsaKey.StringOf("boxAppSettings.appAuth.publicKeyID")) ' Now let's build the JWT claims. Most of this is just boilerplate (i.e. the same every time..) ' The JWT claims contain these required and optional elements: ' iss (required, String) The Client ID of the service that created the JWT assertion. ' sub (required, String) enterprise_id for a token specific to an enterprise when creating and managing app users, or the app user_id for a token specific to an individual app user. ' box_sub_type (required, String) "enterprise" or "user" depending on the type of token being requested in the sub claim. ' aud (required, String) Always "https://api.box.com/oauth2/token" for OAuth2 token requests ' jti (required, String) A universally unique identifier specified by the client for this JWT. This is a unique string that is at least 16 characters and at most 128 characters. ' exp (required, NumericDate) The unix time as to when this JWT will expire. This can be set to a maximum value of 60 seconds beyond the issue time. Note: It is recommended to set this value to less than the maximum allowed 60 seconds. ' iat (optional, NumericDate) Issued at time. The token cannot be used before this time. ' nbf (optional, NumericDate) Not before. Specifies when the token will start being valid. ' Dim claims As Chilkat.JsonObject Set claims = Chilkat.NewJsonObject success = claims.UpdateString("iss",jsonRsaKey.StringOf("boxAppSettings.clientID")) success = claims.UpdateString("sub",jsonRsaKey.StringOf("enterpriseID")) success = claims.UpdateString("box_sub_type","enterprise") success = claims.UpdateString("aud","https://api.box.com/oauth2/token") ' Generate 32 random bytes (base64 encoded) for the "jti" Dim prng As Chilkat.Prng Set prng = Chilkat.NewPrng success = claims.UpdateString("jti",prng.GenRandom(32,"base64")) ' Set the expiration time to 60 seconds after the current time. success = claims.UpdateInt("exp",jwt.GenNumericDate(60)) ' We're going to do the following POST to get a JSON response that contains our OAuth2 access token: ' POST /oauth2/token ' Content-Type: application/x-www-form-urlencoded ' grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer& ' assertion=<JWT>& ' client_id=<client_id>& ' client_secret=<client_secret> ' First, make the initial connection. ' A single REST object, once connected, can be used for many Box REST API calls. ' The auto-reconnect indicates that if the already-established HTTPS connection is closed, ' then it will be automatically re-established as needed. Dim rest As Chilkat.Rest Set rest = Chilkat.NewRest bAutoReconnect = True success = rest.Connect("api.box.com",443,True,bAutoReconnect) If (success <> True) Then Debug.Print rest.LastErrorText Exit Sub End If ' Add the query params. ' Calling ClearAllParts is wise if previous requests were sent prior to this one on the same REST object.. success = rest.ClearAllParts() success = rest.AddQueryParam("grant_type","urn:ietf:params:oauth:grant-type:jwt-bearer") success = rest.AddQueryParam("client_id",jsonRsaKey.StringOf("boxAppSettings.clientID")) success = rest.AddQueryParam("client_secret",jsonRsaKey.StringOf("boxAppSettings.clientSecret")) success = rest.AddQueryParam("assertion",jwt.CreateJwtPk(jose.Emit(),claims.Emit(),rsaKey)) jsonResponse = rest.FullRequestFormUrlEncoded("POST","/oauth2/token") If (rest.LastMethodSuccess <> True) Then Debug.Print rest.LastErrorText Exit Sub End If ' If successful, we'll get a response status code equal to 200, ' and a JSON response that looks like this: ' { ' "access_token": "mNr1FrCvOeWiGnwLL0OcTL0Lux5jbyBa", ' "expires_in": 4169, ' "restricted_to": [], ' "token_type": "bearer" ' } ' Dim jResponse As Chilkat.JsonObject Set jResponse = Chilkat.NewJsonObject jResponse.EmitCompact = False success = jResponse.Load(jsonResponse) If (rest.ResponseStatusCode <> 200) Then Debug.Print jResponse.Emit() Debug.Print "Failed." Exit Sub End If ' Get the access token: accessToken = jResponse.StringOf("access_token") Debug.Print "Access token, valid for 60 minutes: "; accessToken |
© 2000-2022 Chilkat Software, Inc. All Rights Reserved.