JavaScript 사용자 정의 자원 요청 구현 샘플

MobileFirst WLAuthorizationManager 클래스를 사용하여 보호 자원에서 데이터를 가져오기 위한 JavaScript 샘플입니다.

샘플은 표준 OAuth 플로우를 구현합니다. 먼저, 액세스 토큰 없이 자원 요청을 전송합니다. 이 요청은 권한 오류로 인해 실패할 것으로 예상됩니다. 그러면 WLAuthorizationManager를 사용하여 자원의 보호 범위에 대한 액세스 토큰을 가져오고, 가져온 액세스 토큰을 권한 헤더로 사용하여 요청을 다시 전송합니다. 자원 요청은 표준 XMLHttpRequest 오브젝트를 사용하여 작성합니다.

function sendCustomRequest() {
    sendRequest('http://localhost:3000/v1/apps/1234/test', null)
        .always(
            function(response) {
                alert(response);
            }
        );
}

/**
 * Sends a request with the provided access token to the specified protected-resource URL.
 **/
function sendRequest(url, accessToken) {
    // Use JavaScript promises for asynchronous operations
    var dfd = WLJQ.Deferred();

    // Create the custom resource request
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);

    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            var status = xhr.status;
            if (status >= 200 && status <= 299) {
                dfd.resolve(xhr.responseText);
            }
            else {
                var headers = xhr.getAllResponseHeaders();

                // Check whether access to the resource requires authorization
                if (WLAuthorizationManager.isAuthorizationRequired(status, headers)) {
                    if (status === 409) { // Server-conflict error
                        // Resend the request
                        sendRequest(url, accessToken)
                            .then(
                                function(response) {
                                    dfd.resolve(response);
                                },
                                function(error) {
                                    dfd.reject(error);
                                }
                            );
                    } else if (status === 401) { // Invalid access token, or no access token
                        // Check whether the access token is invalid
                        if (isInvalidTokenError(xhr)) {
                            // Clear the invalid access token
                            WLAuthorizationManager.clearAccessToken(accessToken).always(
                                function() {
                                    // Obtain a valid access token and resend the request
                                    resendWithAccessToken(null);
                                });
                        } else {
                            // Obtain a valid access token and resend the request
                            resendWithAccessToken(null);
                        }
                    } else { // status = 403 - insufficient-scope error
                        // Get the resource scope from the response
                        var scope = WLAuthorizationManager.getResourceScope(headers);
                        // Obtain an access token for the scope
                        resendWithAccessToken(scope);
                    }
                } else { // Unexpected error
                    dfd.reject("Failure - received response " + xhr.responseText);
                }
            }
        }
    };

    // If an access token was obtained, add the token to the request as an authorization header
    if (accessToken !== null) {
        xhr.setRequestHeader("Authorization", accessToken.asAuthorizationRequestHeader);
    }

    xhr.send();

    return dfd.promise();


    function resendWithAccessToken(scope) {
        WLAuthorizationManager.obtainAccessToken(scope)
            .then(
                function(accessToken) {
                    // The access token was obtained successfully.
                    // Construct the request again, and add the access token as an authorization header
                    sendRequest(url, accessToken)
                        .then(
                            function(response) {
                                dfd.resolve(response);
                            },
                            function(error) {
                                dfd.reject(error);
                            }
                        );
                },
                function(error) {
                    // Failed to obtain an access token. Reject the request.
                    dfd.reject(error);
                }
            );
    }
}

function isInvalidTokenError(xhr) {
    var authHeader = xhr.getResponseHeader('WWW-Authenticate');
    return (authHeader.indexOf("invalid_token") >= 0);
}