Sample code for 30+ languages & platforms
Ruby Requires Chilkat v11.6.0+

OneDrive: Access Microsoft 365 OneDrive with a Certificate

See more OneDrive Examples

Acquire an application token using an RSA certificate and list a selected organizational user's drives. This is for OneDrive for Business and SharePoint, not personal Microsoft accounts. Configure Graph application Files.Read.All and administrator consent for this listing. Provision the user's OneDrive separately; consent does not create it. Use an appropriate restricted-access design when broad application access is unnecessary.

Private onedrive-certificate-app.json contains tenant_id, client_id, user_id (object ID or UPN), pfx_path, and pfx_password. Upload the public certificate to the Entra application and protect the RSA private key in an environment you control. Use a tenant-specific authority. Never distribute this private key in a public application.

The five-minute PS256 assertion includes x5t#S256, the SHA-256 certificate thumbprint. It is sent only to the token endpoint. The resulting Graph token is sent to Graph. .default selects configured application permissions; no refresh token is issued. Acquire a new token with a fresh assertion before expiry.

Follows complete @odata.nextLink URLs, including after empty pages. It validates the Graph host/API path, rejects repeated links, and reports a stop at the demonstration bound of 100 pages. $top is page size, not the total result count. Enumeration is not a transactionally consistent snapshot during concurrent changes.

Permission: Application Files.Read.All with administrator consent.

Check the expected HTTP status before using a response body. A false method result can still contain an HTTP error response; status zero means no response arrived. For 401, renew authorization; for 403, check permissions, access grants, and policy; for 429, honor Retry-After with a bounded retry. Reconcile uncertain writes before repeating them. Keep credentials, file contents, upload/download URLs, and detailed diagnostics private.

Microsoft documentation

Chilkat Ruby Downloads

Ruby
require 'chilkat'

success = false

#  Assumes Chilkat is unlocked. See Global Unlock Sample.
success = false
config = Chilkat::CkJsonObject.new()
config.put_Strict(true)
success = config.LoadFile("onedrive-certificate-app.json")
if (success != true)
    print "Could not load private app configuration." + "\n";
    exit
end

if ((config.JsonTypeOf("tenant_id") != 1) or (config.StringOfEquals("tenant_id","",true) == true))
    print "Expected a nonempty tenant_id in the JSON." + "\n";
    exit
end

if ((config.JsonTypeOf("client_id") != 1) or (config.StringOfEquals("client_id","",true) == true))
    print "Expected a nonempty client_id in the JSON." + "\n";
    exit
end

if ((config.JsonTypeOf("user_id") != 1) or (config.StringOfEquals("user_id","",true) == true))
    print "Expected a nonempty user_id in the JSON." + "\n";
    exit
end

if ((config.JsonTypeOf("pfx_path") != 1) or (config.StringOfEquals("pfx_path","",true) == true))
    print "Expected a nonempty pfx_path in the JSON." + "\n";
    exit
end

#  pfx_password may be empty for an unencrypted test PFX; protect the private key in production.
http = Chilkat::CkHttp.new()
http.put_RequireSslCertVerify(true)
http.put_FollowRedirects(false)
http.put_ConnectTimeout(20)
http.put_ReadTimeout(30)
tokenEndpoint = Chilkat::CkStringBuilder.new()
tokenEndpoint.Append("https://login.microsoftonline.com/")
tokenEndpoint.Append(http.urlEncode(config.stringOf("tenant_id")))
tokenEndpoint.Append("/oauth2/v2.0/token")
tokenUrl = tokenEndpoint.getAsString()
cert = Chilkat::CkCert.new()
success = cert.LoadPfxFile(config.stringOf("pfx_path"),config.stringOf("pfx_password"))
if (success != true)
    print "Could not load the application certificate." + "\n";
    exit
end

key = Chilkat::CkPrivateKey.new()
success = cert.GetPrivateKey(key)
if (success != true)
    print "The certificate needs an accessible RSA private key." + "\n";
    exit
end

der = Chilkat::CkBinData.new()
success = cert.ExportCertDerBd(der)
if (success != true)
    print "Could not read the certificate DER bytes." + "\n";
    exit
end

crypt = Chilkat::CkCrypt2.new()
crypt.put_HashAlgorithm("sha256")
crypt.put_EncodingMode("base64url")
thumbprint = crypt.hashBdENC(der)
if (crypt.get_LastMethodSuccess() != true)
    print "Could not hash the certificate." + "\n";
    exit
end

header = Chilkat::CkJsonObject.new()
header.UpdateString("alg","PS256")
header.UpdateString("typ","JWT")
header.UpdateString("x5t#S256",thumbprint)
claims = Chilkat::CkJsonObject.new()
claims.UpdateString("aud",tokenUrl)
claims.UpdateString("iss",config.stringOf("client_id"))
claims.UpdateString("sub",config.stringOf("client_id"))
assertionId = crypt.generateUuid()
if (crypt.get_LastMethodSuccess() != true)
    print "Could not create the assertion ID." + "\n";
    exit
end

claims.UpdateString("jti",assertionId)
clock = Chilkat::CkDateTime.new()
success = clock.SetFromCurrentSystemTime()
if (success != true)
    print "Could not read the clock." + "\n";
    exit
end

#  Numeric dates are JSON numbers built from decimal strings, without converting timestamps to a platform-sized integer.
claims.UpdateNumber("iat",clock.getAsUnixTimeStr(false))
claims.UpdateNumber("nbf",clock.getAsUnixTimeStr(false))
success = clock.AddSeconds(300)
if (success != true)
    print "Could not set assertion expiry." + "\n";
    exit
end

claims.UpdateNumber("exp",clock.getAsUnixTimeStr(false))
jwt = Chilkat::CkJwt.new()
assertion = jwt.createJwtPk(header.emit(),claims.emit(),key)
if (jwt.get_LastMethodSuccess() != true)
    print "Could not sign the client assertion." + "\n";
    exit
end

req = Chilkat::CkHttpRequest.new()
req.put_HttpVerb("POST")
req.put_ContentType("application/x-www-form-urlencoded")
req.AddParam("client_id",config.stringOf("client_id"))
req.AddParam("grant_type","client_credentials")
req.AddParam("scope","https://graph.microsoft.com/.default")
req.AddParam("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer")
req.AddParam("client_assertion",assertion)
resp = Chilkat::CkHttpResponse.new()
result = Chilkat::CkJsonObject.new()
result.put_Strict(true)
success = http.HttpReq(tokenUrl,req,resp)
#  A false result can still include an HTTP error response.
if ((success != true) and (resp.get_StatusCode() == 0))
    print "No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying." + "\n";
    exit
end

if (resp.get_StatusCode() != 200)
    print "Unexpected HTTP status: " + resp.get_StatusCode().to_s() + "\n";
    print "Request ID: " + resp.getHeaderField("request-id") + "\n";
    if (resp.get_StatusCode() == 429)
        print "Retry-After: " + resp.getHeaderField("Retry-After") + "\n";
    end

    if (resp.get_StatusCode() == 401)
        print "Refresh the Graph access token or authorize again." + "\n";
    end

    exit
end

success = result.Load(resp.bodyStr())
if (success != true)
    print "Expected a well-formed JSON response." + "\n";
    exit
end

if ((result.JsonTypeOf("access_token") != 1) or (result.StringOfEquals("access_token","",true) == true))
    print "Expected a nonempty access_token in the JSON." + "\n";
    exit
end

http.put_AuthToken(result.stringOf("access_token"))
#  Application access addresses a specific organizational user; /me is not available.
http.SetRequestHeader("Accept","application/json")
endpoint = Chilkat::CkStringBuilder.new()
endpoint.Append("https://graph.microsoft.com/v1.0/users/")
endpoint.Append(http.urlEncode(config.stringOf("user_id")))
endpoint.Append("/drives?$select=id,name,driveType,quota&$top=50")
url = endpoint.getAsString()
nextLink = Chilkat::CkStringBuilder.new()
seenLinks = Chilkat::CkHashtable.new()
pageCount = 0
while ((url != "") and (pageCount < 100))
    nextLink.SetString(url)
    if (nextLink.StartsWith("https://graph.microsoft.com/v1.0/",true) != true)
        print "Unexpected pagination host or API version; no request sent." + "\n";
        exit
    end

    if (seenLinks.Contains(url) == true)
        print "Repeated pagination URL; stopping." + "\n";
        exit
    end

    seenLinks.AddInt(url,1)
    success = http.HttpNoBody("GET",url,resp)
    if ((success != true) and (resp.get_StatusCode() == 0))
        print "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying." + "\n";
        exit
    end

    if ((resp.get_StatusCode() != 200))
        print "Unexpected HTTP status: " + resp.get_StatusCode().to_s() + "\n";
        print "Request ID: " + resp.getHeaderField("request-id") + "\n";
        if (resp.get_StatusCode() == 429)
            print "Retry-After: " + resp.getHeaderField("Retry-After") + "\n";
        end

        exit
    end

    success = result.Load(resp.bodyStr())
    if (success != true)
        print "Expected a well-formed JSON response." + "\n";
        exit
    end

    if (result.JsonTypeOf("value") != 4)
        print "Expected a value array." + "\n";
        exit
    end

    i = 0
    while (i < result.SizeOfArray("value"))
        result.put_I(i)
        if ((result.JsonTypeOf("value[i].id") != 1) or (result.StringOfEquals("value[i].id","",true) == true))
            print "Expected a nonempty value[i].id in the JSON." + "\n";
            exit
        end

        print "Drive ID: " + result.stringOf("value[i].id") + "\n";
        print "Name: " + result.stringOf("value[i].name") + "\n";
        print "Drive type: " + result.stringOf("value[i].driveType") + "\n";
        #  Quota values can be larger than int. Missing quota fields are not zero.
        if (result.HasMember("value[i].quota.total") == true)
            print "Total bytes: " + result.stringOf("value[i].quota.total") + "\n";
            print "Remaining bytes: " + result.stringOf("value[i].quota.remaining") + "\n";
        end

        i = i + 1
    end
    pageCount = pageCount + 1
    #  A quoted JSON path treats the period in @odata.nextLink literally.
    nextType = result.JsonTypeOf("\"@odata.nextLink\"")
    if ((nextType == -1) or (nextType == 6))
        url = ""
    else
        if ((nextType != 1) or (result.StringOfEquals("\"@odata.nextLink\"","",true) == true))
            print "Invalid continuation link; cannot establish completeness." + "\n";
            exit
        end

        url = result.stringOf("\"@odata.nextLink\"")
    end

end
if (url != "")
    print "Stopped at the example's 100-page limit; save the continuation privately to resume." + "\n";
    exit
end

print "Completed pages: " + pageCount.to_s() + "\n";