programing

AngularJS $http, CORS 및 http 인증

telebox 2023. 3. 8. 21:03
반응형

AngularJS $http, CORS 및 http 인증

Angular와 함께 CORS 및 http 인증을 사용하기 때문에JS가 좀 까다로울 수 있어요. 배운 내용을 공유하기 위해 문제를 수정했습니다.먼저 이고르즈그에게 감사하고 싶다.그의 대답이 나에게 많은 도움을 주었다.시나리오는 다음과 같습니다.POST 요청을 Angular를 사용하여 다른 도메인으로 전송하려고 합니다.JS $http 서비스Angular를 얻을 때 주의해야 할 몇 가지 까다로운 사항이 있습니다.JS 및 서버 셋업.

첫 번째: 응용 프로그램 설정에서 교차 도메인 호출을 허용해야 합니다.

/**
 *  Cors usage example. 
 *  @author Georgi Naumov
 *  gonaumov@gmail.com for contacts and 
 *  suggestions. 
 **/ 
app.config(function($httpProvider) {
    //Enable cross domain calls
    $httpProvider.defaults.useXDomain = true;
});

두 번째: credentials: true 및 사용자 이름과 비밀번호를 요청으로 지정해야 합니다.

 /**
  *  Cors usage example. 
  *  @author Georgi Naumov
  *  gonaumov@gmail.com for contacts and 
  *  suggestions. 
  **/ 
   $http({
        url: 'url of remote service',
        method: "POST",
        data: JSON.stringify(requestData),
        withCredentials: true,
        headers: {
            'Authorization': 'Basic bashe64usename:password'
        }
    });

Hird: 서버 셋업.다음을 제공해야 합니다.

/**
 *  Cors usage example. 
 *  @author Georgi Naumov
 *  gonaumov@gmail.com for contacts and 
 *  suggestions. 
 **/ 
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: http://url.com:8080");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");

모든 요청에 대응합니다.OPTION을 받을 때 합격해야 합니다.

/**
 *  Cors usage example. 
 *  @author Georgi Naumov
 *  gonaumov@gmail.com for contacts and 
 *  suggestions. 
 **/ 
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
   header( "HTTP/1.1 200 OK" );
   exit();
}

HTTP 인증 및 기타 모든 것이 그 후에 이루어집니다.

다음은 php를 사용한 서버 측 사용의 완전한 예입니다.

<?php
/**
 *  Cors usage example. 
 *  @author Georgi Naumov
 *  gonaumov@gmail.com for contacts and 
 *  suggestions. 
 **/ 
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: http://url:8080");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");

if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
   header( "HTTP/1.1 200 OK" );
   exit();
}


$realm = 'Restricted area';

$password = 'somepassword';

$users = array('someusername' => $password);


if (isset($_SERVER['PHP_AUTH_USER']) == false ||  isset($_SERVER['PHP_AUTH_PW']) == false) {
    header('WWW-Authenticate: Basic realm="My Realm"');

    die('Not authorised');
}

if (isset($users[$_SERVER['PHP_AUTH_USER']]) && $users[$_SERVER['PHP_AUTH_USER']] == $password) 
{
    header( "HTTP/1.1 200 OK" );
    echo 'You are logged in!' ;
    exit();
}
?>

제 블로그에 이 문제에 관한 기사가 있는데, 여기서 보실 수 있습니다.

아니요, 자격 증명을 입력할 필요가 없습니다. 클라이언트 측에 헤더를 배치해야 합니다. 예:

 $http({
        url: 'url of service',
        method: "POST",
        data: {test :  name },
        withCredentials: true,
        headers: {
                    'Content-Type': 'application/json; charset=utf-8'
        }
    });

서버 측에서는 헤더를 여기에 배치해야 합니다.nodej의 경우 다음과 같습니다.

/**
 * On all requests add headers
 */
app.all('*', function(req, res,next) {


    /**
     * Response settings
     * @type {Object}
     */
    var responseSettings = {
        "AccessControlAllowOrigin": req.headers.origin,
        "AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name",
        "AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
        "AccessControlAllowCredentials": true
    };

    /**
     * Headers
     */
    res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
    res.header("Access-Control-Allow-Origin",  responseSettings.AccessControlAllowOrigin);
    res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
    res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);

    if ('OPTIONS' == req.method) {
        res.send(200);
    }
    else {
        next();
    }


});

CORS 요청을 작성하려면 요청에 헤더를 추가해야 합니다.또한 Apache에서 mode_header가 활성화 되어 있는지 확인해야 합니다.

Ubuntu에서 헤더를 활성화하는 경우:

sudo a2enmod headers

php 서버가 다른 오리진으로부터의 요구를 받아들이려면 , 다음의 순서를 사용합니다.

Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

언급URL : https://stackoverflow.com/questions/21455045/angularjs-http-cors-and-http-authentication

반응형