programing

CORS: credentials 플래그가 true인 경우 Access-Control-Allow-Origin에서 와일드카드를 사용할 수 없습니다.

iphone6s 2023. 3. 18. 08:23
반응형

CORS: credentials 플래그가 true인 경우 Access-Control-Allow-Origin에서 와일드카드를 사용할 수 없습니다.

내 계획은...

프런트 엔드 서버(Node.js, 도메인:localhost:3000) <--> 백엔드(장고, Ajax, 도메인:localhost:8000)

브라우저 <--webapp<--Node.js(앱을 제공합니다)

브라우저(webapp) --> Ajax --> 장고(Serve ajax POST 요청)

여기서의 문제는 웹 앱이 백엔드 서버에 Ajax를 호출할 때 사용하는 CORS 설정에 있습니다.크롬에서는 계속...

자격 증명 플래그가 true이면 Access-Control-Allow-Origin에서 와일드카드를 사용할 수 없습니다.

파이어폭스에서도 동작하지 않습니다.

My Node.js 설정은 다음과 같습니다.

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://localhost:8000/');
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
};

그리고 장고에서는 이 미들웨어를 이것과 함께 사용하고 있습니다.

웹 앱은 다음과 같은 요청을 합니다.

$.ajax({
    type: "POST",
    url: 'http://localhost:8000/blah',
    data: {},
    xhrFields: {
        withCredentials: true
    },
    crossDomain: true,
    dataType: 'json',
    success: successHandler
});

따라서 웹 앱에서 보내는 요청 헤더는 다음과 같습니다.

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: "Origin, X-Requested-With, Content-Type, Accept"
Access-Control-Allow-Methods: 'GET,PUT,POST,DELETE'
Content-Type: application/json 
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie: csrftoken=***; sessionid="***"

응답 헤더는 다음과 같습니다.

Access-Control-Allow-Headers: Content-Type,*
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE
Content-Type: application/json

어디가 잘못됐지?!

1:중 1: 사용 중chrome --disable-web-security하지만 이제는 실제로 작동하기를 원합니다.

편집 2: 답변:

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★」django-cors-headers★★★★

CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
    'http://localhost:3000' # Here was the problem indeed and it has to be http://localhost:3000, not http://localhost:3000/
)

이것은 보안의 일부입니다.그러면 안 됩니다.는, 「」를 해 주세요.Access-Control-Allow-Origin는 사용할 수 .* 정확한 + + 정확한 프로토콜 + 도메인 + 포트를 지정해야 합니다.다음 을 참고하세요.

  1. Access-Control-Allow-Origin 와일드카드 서브 도메인, 포트 및 프로토콜
  2. credential을 사용한 오리진 간 공유

말고.*너무 관대해서 자격증 사용을 방해할 수 있습니다.을 합니다.http://localhost:3000 ★★★★★★★★★★★★★★★★★」http://localhost:8000기원을 인정하다

, 「CORS」를 는, 「CORS」를 송부합니다.withCredentialtrue는 CORS를 설정할 수 있습니다.boolean true, cors는 다음과 같습니다.

var cors = require('cors');    
app.use(cors({credentials: true, origin: 'http://localhost:3000'}));

@Renaud 아이디어를 확장한 Cors는 이를 위한 매우 쉬운 방법을 제공합니다.

여기 있는 Cors 공식 문서:

"원점: Access-Control-Allow-Origin CORS 헤더를 설정합니다. 가능한 값: Boolean - req.header('Origin')에서 정의된 요청 원점을 반영하려면 원점을 true로 설정하거나 CORS를 사용하지 않으려면 false로 설정합니다."

그 때문에, 다음의 조작을 실시합니다.

const app = express();
const corsConfig = {
    credentials: true,
    origin: true,
};
app.use(cors(corsConfig));

마지막으로 퍼블릭 REST API 구축 등 모든 사용자의 크로스 오리진 요구를 허용하고 싶은 사용 사례가 있다는 점을 언급할 필요가 있다고 생각합니다.

시험해 보세요.

const cors = require('cors')

const corsOptions = {
    origin: 'http://localhost:4200',
    credentials: true,

}
app.use(cors(corsOptions));

「 」를 사용하고 express미들웨어를 쓰는 대신 코르스 패키지를 사용하여 CORS를 허용할 수 있습니다.

var express = require('express')
, cors = require('cors')
, app = express();

app.use(cors());

app.get(function(req,res){ 
  res.send('hello');
});

모든 원본을 허용하고 자격 증명을 True로 유지하려면 다음과 같이 하십시오.

app.use(cors({
  origin: function(origin, callback){
    return callback(null, true);
  },
  optionsSuccessStatus: 200,
  credentials: true
}));

이것은 개발에서는 효과가 있지만, 생산에서는 아직 언급되지 않았지만 아마도 최선은 아닐지도 모르는 일을 완수하는 다른 방법이라고 조언할 수는 없습니다.어쨌든, 다음과 같이 하자.

요청에서 오리진을 가져와 응답 헤더에서 사용할 수 있습니다.표현은 다음과 같습니다.

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', req.header('origin') );
  next();
});

당신의 python 설정에서는 어떻게 보일지 모르겠지만 번역은 쉬울 것입니다.

(편집) 이전에 권장했던 애드온을 사용할 수 없게 되었습니다.다른 애드온을 사용해 보세요.


Chrome에서 개발 목적으로 이 애드온을 설치하면 특정 오류가 제거됩니다.

Access to XMLHttpRequest at 'http://192.168.1.42:8080/sockjs-node/info?t=1546163388687' 
from origin 'http://localhost:8080' has been blocked by CORS policy: The value of the 
'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' 
when the request's credentials mode is 'include'. The credentials mode of requests 
initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

후, 에 추가해 .Intercepted URLs추가 기능(CORS, 녹색 또는 빨간색) 아이콘을 클릭하고 적절한 텍스트 상자를 채웁니다.여기에 추가할 URL 패턴의 예로서 함께 동작합니다.http://localhost:8080 됩니다.*://*

cors origin에 대한 해결방법은 많지만 부족한 부분을 추가할 수 있을 것 같습니다.일반적으로 node.js에서 cors middlware를 사용하면 다양한 http 메서드(get, post, put, delete)와 같이 최대한의 목적을 달성할 수 있습니다.

그러나 cookie 응답 전송과 같은 사용 사례가 있습니다. cors 미들웨어 내에서 credential을 true로 활성화해야 합니다.또는 cookie를 설정할 수 없습니다.또한 모든 원본에 액세스할 수 있는 사용 사례도 있습니다.그렇다면, 우리는 사용해야 한다.

{credentials: true, origin: true}

특정 발신기지에는 발신지 이름을 지정해야 합니다.

{credential: true, origin: "http://localhost:3000"}

복수 기원의 경우,

{credential: true, origin: ["http://localhost:3000", "http://localhost:3001" ]}

경우에 따라서는, 복수의 송신원을 허가할 필요가 있습니다.한 가지 사용 사례는 개발자만 허용하는 것입니다.동적 화이트리스트를 작성하기 위해 다음과 같은 기능을 사용할 수 있습니다.

const whitelist = ['http://developer1.com', 'http://developer2.com']
const corsOptions = {
origin: (origin, callback) => {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error())
    }
  }
}

요구가 실행되기 전에 auth interceptive를 사용하여 헤더를 편집하는 각도 문제가 발생하였습니다.인증에 api-token을 사용했기 때문에 credential을 유효하게 했습니다.이제 더 이상 필요하지 않은 것 같다/허용되지 않은 것 같습니다.

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    req = req.clone({
      //withCredentials: true, //not needed anymore
      setHeaders: {
        'Content-Type' : 'application/json',
        'API-TOKEN' : 'xxx'
      },
    });
    
    return next.handle(req);
  }

그 외에는 현재 부작용은 없습니다.

NETLIFY 및 HEROKU에서의 CORS 오류

실제로 위의 솔루션 중 어느 것도 효과가 없는 경우는, 이것을 사용해 보는 것이 좋습니다.제 경우 백엔드는 Heroku에서 실행되고 프론트엔드는 netlify에서 호스트됩니다.프런트 엔드의 .env 파일에서는 server_url은 다음과 같이 기술되어 있습니다.

REACT_APP_server_url = "https://ci-cd-backend.herokuapp.com"

백엔드에서 내 API 호출은 모두

app.get('/login', (req, res, err) => {});

변경은 루트 끝에 /api를 추가하면 됩니다.

따라서 프런트엔드의 베이스 URL은 다음과 같습니다.

REACT_APP_server_url = "https://ci-cd-backend.herokuapp.com/api"

및 백엔드 아피스는 다음과 같이 작성해야 합니다.

app.get('/api/login', (req, res, err) => {})

이것은 제 경우 효과가 있었습니다만, 프런트 엔드가 netlify로 호스트 되고 있는 경우는, 이 문제가 특히 관련이 있다고 생각합니다.

언급URL : https://stackoverflow.com/questions/19743396/cors-cannot-use-wildcard-in-access-control-allow-origin-when-credentials-flag-i

반응형