You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cordova Native应用:Keycloak获取Token代码替换为Cordova Advanced HTTP插件

使用cordova-plugin-advanced-http替换Keycloak中XMLHttpRequest的Token获取实现

针对后端拦截localhost请求的问题,以下是将原Keycloak的processCallback函数替换为使用cordova-plugin-advanced-http插件的实现:

function processCallback(oauth, promise) {
    var code = oauth.code;
    var error = oauth.error;
    var prompt = oauth.prompt;

    var timeLocal = new Date().getTime();

    if (oauth['kc_action_status']) {
        kc.onActionUpdate && kc.onActionUpdate(oauth['kc_action_status']);
    }

    if (error) {
        if (prompt != 'none') {
            var errorData = { error: error, error_description: oauth.error_description };
            kc.onAuthError && kc.onAuthError(errorData);
            promise && promise.setError(errorData);
        } else {
            promise && promise.setSuccess();
        }
        return;
    } else if ((kc.flow != 'standard') && (oauth.access_token || oauth.id_token)) {
        authSuccess(oauth.access_token, null, oauth.id_token, true);
    }

    if ((kc.flow != 'implicit') && code) {
        // 构建请求参数对象
        var params = {
            code: code,
            grant_type: 'authorization_code',
            client_id: kc.clientId,
            redirect_uri: oauth.redirectUri
        };

        // 追加PKCE校验码(如果存在)
        if (oauth.pkceCodeVerifier) {
            params.code_verifier = oauth.pkceCodeVerifier;
        }

        var url = kc.endpoints.token();

        // 使用cordova-plugin-advanced-HTTP发送POST请求
        cordova.plugin.http.post(url, params, {
            'Content-Type': 'application/x-www-form-urlencoded'
        }, function(response) {
            // 解析响应数据并执行授权成功逻辑
            var tokenResponse = JSON.parse(response.data);
            authSuccess(tokenResponse['access_token'], tokenResponse['refresh_token'], tokenResponse['id_token'], kc.flow === 'standard');
            scheduleCheckIframe();
        }, function(error) {
            // 处理请求错误
            kc.onAuthError && kc.onAuthError();
            promise && promise.setError();
        });

        // 启用跨域凭证传递,对应原XMLHttpRequest的withCredentials=true
        cordova.plugin.http.setCookie('*', '', '', true);
    }

    function authSuccess(accessToken, refreshToken, idToken, fulfillPromise) {
        timeLocal = (timeLocal + new Date().getTime()) / 2;

        setToken(accessToken, refreshToken, idToken, timeLocal);

        if (useNonce && ((kc.tokenParsed && kc.tokenParsed.nonce != oauth.storedNonce) ||
            (kc.refreshTokenParsed && kc.refreshTokenParsed.nonce != oauth.storedNonce) ||
            (kc.idTokenParsed && kc.idTokenParsed.nonce != oauth.storedNonce))) {

            logInfo('[KEYCLOAK] Invalid nonce, clearing token');
            kc.clearToken();
            promise && promise.setError();
        } else {
            if (fulfillPromise) {
                kc.onAuthSuccess && kc.onAuthSuccess();
                promise && promise.setSuccess();
            }
        }
    }
}

核心改动说明:

  • 移除原XMLHttpRequest逻辑,改用cordova.plugin.http.post发起原生HTTP请求
  • 将原手动拼接的URL参数转换为对象格式,插件自动完成参数编码
  • 保留原请求头Content-Type设置,保持与后端的格式兼容
  • 通过cordova.plugin.http.setCookie实现跨域凭证传递,对齐原withCredentials=true的功能
  • 使用插件自带的成功/失败回调替代原onreadystatechange的状态判断逻辑

内容的提问来源于stack exchange,提问作者Kiran Chenna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 21:20:27