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

OneDrive: Refresh a Delegated Access Token

See more OneDrive Examples

Refresh the token from OneDrive authorization with PKCE, using the same application client ID and authority. This retains the user grant; it does not convert it to application access. Omitting scope retains the existing scopes. Obtain additional consent through authorization when needed.

The private oneDrive.json token cache is replaced only after a successful, validated response. Retain the previous refresh token when no replacement is returned, and save a rotated refresh token when supplied. A private backup is written first; production storage should use atomic replacement and a single refresh writer per account/application. invalid_grant or an interaction requirement requires sign-in again. Tokens and raw responses are not printed.

Permission: The original delegated grant.

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 Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = false
    let token = CkoJsonObject()!
    token.strict = true
    success = token.loadFile(path: "qa_data/tokens/oneDrive.json")
    if success != true {
        print("Read the private token cache or authorize again.")
        return
    }

    if (token.jsonType(of: "refresh_token").intValue != 1) || (token.string(ofEquals: "refresh_token", value: "", caseSensitive: true) == true) {
        print("Expected a nonempty refresh_token in the JSON.")
        return
    }

    var clientId: String? = "YOUR_APPLICATION_CLIENT_ID"
    //  Use the same app and authority as the original authorization.
    var tokenUrl: String? = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
    let http = CkoHttp()!
    http.requireSslCertVerify = true
    http.followRedirects = false
    http.connectTimeout = 20
    http.readTimeout = 30
    let req = CkoHttpRequest()!
    req.httpVerb = "POST"
    req.contentType = "application/x-www-form-urlencoded"
    req.addParam(name: "client_id", value: clientId)
    req.addParam(name: "grant_type", value: "refresh_token")
    req.addParam(name: "refresh_token", value: token.string(of: "refresh_token"))
    //  Omitting scope retains the original grant instead of requesting additional permissions.
    let resp = CkoHttpResponse()!
    let result = CkoJsonObject()!
    result.strict = true
    success = http.httpReq(url: tokenUrl, request: req, response: resp)
    //  A false result can still include an HTTP error response.
    if (success != true) && (resp.statusCode.intValue == 0) {
        print("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.")
        return
    }

    if resp.statusCode.intValue != 200 {
        print("Unexpected HTTP status: \(resp.statusCode.intValue)")
        print("Request ID: \(resp.getHeaderField(fieldName: "request-id")!)")
        if resp.statusCode.intValue == 429 {
            print("Retry-After: \(resp.getHeaderField(fieldName: "Retry-After")!)")
        }

        if resp.statusCode.intValue == 401 {
            print("Refresh the Graph access token or authorize again.")
        }

        return
    }

    success = result.load(json: resp.bodyStr)
    if success != true {
        print("Expected a well-formed JSON response.")
        return
    }

    if (result.jsonType(of: "access_token").intValue != 1) || (result.string(ofEquals: "access_token", value: "", caseSensitive: true) == true) {
        print("Expected a nonempty access_token in the JSON.")
        return
    }

    if (result.jsonType(of: "expires_in").intValue != 2) || (result.int(of: "expires_in").intValue <= 0) {
        print("Missing token lifetime; old cache unchanged.")
        return
    }

    if result.jsonType(of: "refresh_token").intValue == -1 {
        result.updateString(jsonPath: "refresh_token", value: token.string(of: "refresh_token"))
    }
    else {
        if (result.jsonType(of: "refresh_token").intValue != 1) || (result.string(ofEquals: "refresh_token", value: "", caseSensitive: true) == true) {
            print("Expected a nonempty refresh_token in the JSON.")
            return
        }

    }

    let obtained = CkoDateTime()!
    success = obtained.setFromCurrentSystemTime()
    if success != true {
        print("Could not timestamp the refreshed token.")
        return
    }

    result.updateString(jsonPath: "obtained_at", value: obtained.get(asTimestamp: false))
    //  Keep a valid previous cache for recovery if the replacement write fails.
    success = token.writeFile(path: "qa_data/tokens/oneDrive.json.bak")
    if success != true {
        print("Could not back up the old cache; no replacement attempted.")
        return
    }

    success = result.writeFile(path: "qa_data/tokens/oneDrive.json")
    if success != true {
        print("Could not save the new token; recover the previous cache from the private .bak file.")
        return
    }

    print("Refreshed the OneDrive token cache.")

}