CORS预检后的302重定向 [英] 302 redirect after CORS preflight

查看:3343
本文介绍了CORS预检后的302重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的CORS预检成功返回200状态后,我遇到302重定向的问题。我目前正在使用Laravel 4.1和Angular 1.2以及我自己的OAUTH2服务器构建一个应用程序。



Chrome / FF / Safari传回给我的错误是:


XMLHttpRequest无法加载 http://localhost.api/api/v1/tracks?$ filter = id%20eq%20guid%27d7de10ba-e353-455b-a3cb-ced9b4965141%27& 。请求被重定向到 http://localhost.api/session/invalid ,对于需要预检的跨源请求不允许。


我假设什么造成我的问题是重定向这发生 - 作为我正常的CORS请求所有工作按预期。



我的Access-Control-Allow- *头的配置在测试期间是相当开放的。

 'paths'=> array(
'^ / api /'=> array(
'allow_origin'=> array('*'),
'allow_headers'=& ','Authorization'),
'allow_methods'=> array('POST','PUT','GET','DELETE','OPTIONS'),
'max_age'=> 0
),
'^ / session /'=> array(
'allow_origin'=> array('*'),
'allow_headers'=& ('Content-Type','Authorization'),
'allow_methods'=> array('GET','OPTIONS'),
'max_age'=> 0

有问题的重定向是在检查OAUTH2访问令牌有效性的预过滤器中

 公共函数过滤器($ route,$ request,$ data = null)
{
//获取授权头文件或失败
if($ authorization = Request :: header('Authorization',false)){
list($ type,$ token)= explode('',$ authorization);
if(is_null($ auth = OAuth2 :: token($ token) - > first())){
return Redirect :: to('session / invalid');
}
$ tokenExpiryDate = Carbon :: createFromTimeStamp($ auth-> access_token_expires);

//如果我们没有承载认证头
//或者令牌已经过期。然后重定向到
//过期的会话路由
if('bearer'!= strtolower($ type)
|| Carbon :: now() - > gt($ tokenExpiryDate)
){
return Redirect :: route(
'expiredSession',
array('expiry'=> $ tokenExpiryDate-> timestamp)
);
}
} else {
//认证头无效,重定向让用户知道。
return Redirect :: to('session / invalid');当我尝试使用POSTMAN进行调试时,所有这些请求都工作,所有这些请求都可以正常工作。但在我的研究后,我基本上发现,扩展不一定要玩相同的规则。以及我注意到我的请求使用POSTMAN从来没有发送任何预检OPTIONS请求,当我发起一个简单的GET,POST等。



这里是两个OPTIONS请求以及GET请求,以返回我的错误



OPTIONS请求



 远程地址:127.0.0.1:80 
请求URL:http://localhost.api/api/v1/tracks?$ filter = id%20eq%20guid%27d7de10ba-e353-455b- a3cb-ced9b4965141%27&
请求方法:OPTIONS
状态代码:200 OK

接受:gzip,deflate,sdch




$ b

  b Accept-Language:en-US,en; q = 0.8 
访问控制请求头:接受,授权
访问控制请求方法:GET
高速缓存控制: no-cache
连接:keep-alive
DNT:1
主机:vegas.ine.com
原因:http://localhost.angular
Pragma:no -cache
Referer:http://localhost.angular/admin/
用户代理:Mozilla / 5.0(Macintosh; Intel Mac OS X 10_9_2)AppleWebKit / 537.36(KHTML,像Gecko)Chrome / 34.0 .1847.131 Safari / 537.36

响应标题

 访问控制允许头:内容类型,授权
访问控制允许方法:POST,PUT,GET,DELETE,选项
Access-Control-Allow-Origin:http://localhost.angular
Cache-Control:no-cache
连接:close
Content-Type:text / html
日期:Thu,2014年5月01日16:22:19 GMT
服务器:Apache / 2.2.26(Unix)DAV / 2 PHP / 5.4.24 mod_ssl / 2.2.26 OpenSSL / 0.9.8y
的Set-Cookie:laravel_session = eyJpdiI6IktOZjlTM1ZVNUx0TEhoaTczY3dQcDBKRWlvbnppbDA3QTdqSENJdTc2R1U9IiwidmFsdWUiOiJEZ2ltXC9mNm1Qa20rV3BVRlNHTXgySGtUeVlpNjNZcGFudDFBWDJJekl1MEVNVlhSRE5WWk5YZDNxUkZuU0VEVytcL3NLNlVBXC9hZWtJQzdHU2FqVWtMdz09IiwibWFjIjoiYTYxYjEwNjlmYmI2MjMwNmE4MzlkYjIwNGZlNzA4Y2ViZGVkZmU1MTQzMzc5NmU2YzI2ZGExNzYxY2U5ZjdiMCJ9; expires = Thu,01-May-2014 18:22:19 GMT; path = /; httponly
X-Frame-Options:SAMEORIGIN
X-Powered-By:PHP / 5.4.24


b $ b

GET请求



 远程地址:127.0.0.1:80 
请求URL:http: /localhost.api/api/v1/tracks?$filter=id%20eq%20guid%27d7de10ba-e353-455b-a3cb-ced9b4965141%27&
请求方法:GET
状态代码:302找到



 接受:application / json,text / plain,* / * 
Accept-Encoding: gzip,deflate,sdch
接受语言:en-US,en; q = 0.8
授权:承载6Ss4XPrPM5jQD7Es0dz7TPRQ76hGA69vT9K94pst
缓存控制:无缓存
连接:keep-alive
DNT:1
主机:vegas.ine.com
原产地:http://localhost.angular
Pragma:no-cache
Referer:http:// localhost.angular / admin /
User-Agent:Mozilla / 5.0(Macintosh; Intel Mac OS X 10_9_2)AppleWebKit / 537.36(KHTML,like Gecko)Chrome / 34.0.1847.131 Safari / 537.36



回应标题

 code> Access-Control-Allow-Origin:http://localhost.angular 
Cache-Control:no-cache
连接:Keep-Alive
Content-Type:text / html; charset = UTF-8
Date:Thu,01 May 2014 16:22:19 GMT
Keep-Alive:timeout = 5,max = 100
位置:http://localhost.api /会话/无效
服务器:Apache / 2.2.26(Unix的)DAV / 2 PHP / 5.4.24的mod_ssl / 2.2.26的OpenSSL / 0.9.8y
的Set-Cookie:laravel_session = eyJpdiI6InlnREVPcUJTcyswMnRLanFDSlZ6QWFBVXZWMGdMNVNLYWxNTHRJVUlkalk9IiwidmFsdWUiOiJ4aXN5U0dcL1NYeGQrcUVzWFhYV3o2MWhcL25hQTlhcVUxbWxkN2R6SG9KZDNKaGNLTkRQY2FyTitpVHNGZzYxVVRtZUhoZGZRWE9GWjZRaDd1VVwvZUZuUT09IiwibWFjIjoiY2EzZTViZGIzZmVlMDcwZjdhMzBjOWQxYTgwZWNlYTJiMDk3ODdlZTk3NTYxMDNmM2YyODJjOGIxMzBmMmJlMiJ9; expires = Thu,01-May-2014 18:22:20 GMT; path = /; httponly
Transfer-Encoding:chunked
Vary:Authorization
X-Clockwork-Id:1398961340.2239.1349476325
X-Clockwork-Version:1.5
X-Frame-Options :SAMEORIGIN
X-Powered-By:PHP / 5.4.24


解决方案

我做了这样的事情,它对我很好。

  //模式允许起源
$ allowedOriginPattern = / **你的模式** /;
$ allowedOrigin =;
if(preg_match($ allowedOriginPattern,$ _SERVER ['HTTP_ORIGIN'])){
$ allowedOrigin = $ _SERVER ['HTTP_ORIGIN'];
}

/ **
*设置http内容类型
* /
头('Content-Type:application / json; charset = UTF- 8');
header('Access-Control-Allow-Origin:'。$ allowedOrigin);
header('Access-Control-Allow-Methods:DELETE,HEAD,GET,OPTIONS,POST,PUT');
header('Access-Control-Allow-Headers:Content-Type,Content-Range,Content-Disposition,Content-Description');
headers('Access-Control-Max-Age:1728000');

我已将此代码添加到laravel index.php



这里是CORS的参考资料
http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0


I'm running into a problem with a 302 redirect after my CORS preflight has successfully returned a 200 status. I'm currently building an app using Laravel 4.1 and Angular 1.2 as well as my own OAUTH2 server.

The error that Chrome/FF/Safari are sending back to me is:

XMLHttpRequest cannot load http://localhost.api/api/v1/tracks?$filter=id%20eq%20guid%27d7de10ba-e353-455b-a3cb-ced9b4965141%27&. The request was redirected to 'http://localhost.api/session/invalid', which is disallowed for cross-origin requests that require preflight.

I assume whats causing my issue is the "redirect" thats happening - as my normal CORS requests all work as expected.

My configuration for my Access-Control-Allow-* headers is fairly open right now during testing.

  'paths' => array(
      '^/api/' => array(
          'allow_origin'=> array('*'),
          'allow_headers'=> array('Content-Type', 'Authorization'),
          'allow_methods'=> array('POST', 'PUT', 'GET', 'DELETE', 'OPTIONS'),
          'max_age' => 0     
      ),                
      '^/session/' => array(
          'allow_origin'=> array('*'),
          'allow_headers'=> array('Content-Type', 'Authorization'),
          'allow_methods'=> array('GET', 'OPTIONS'),               
          'max_age' => 0                                                        
      ) 

The redirect in question is in a pre-filter thats checking the validity of an OAUTH2 access token

public function filter($route, $request, $data = null)                       
{                                                                            
    //  Get the authorization header or fail                                 
    if ($authorization = Request::header('Authorization', false)) {          
        list($type, $token) = explode(' ', $authorization);                  
        if (is_null($auth = OAuth2::token($token)->first())) {               
            return Redirect::to('session/invalid');                                                              
        }                                                                    
        $tokenExpiryDate = Carbon::createFromTimeStamp($auth->access_token_expires);

        //  If we don't have a Bearer authentication header                  
        //  or if the token has expired.  Then redirect to an                
        //  expired session route                                            
        if (   'bearer' != strtolower($type)                                 
            || Carbon::now()->gt($tokenExpiryDate)                           
        ) {                                                                  
            return Redirect::route(                                          
                'expiredSession',                                            
                array('expiry' => $tokenExpiryDate->timestamp)               
            );                                                               
        }                                                                    
    } else {                                                                 
        //  The authentication header is invalid, redirect to let the user know.
        return Redirect::to('session/invalid');                              
    }                                                                        
}  

All these requests worked when I tried debugging using POSTMAN, but after my research I've basically found that extensions don't necessarily have to play by the same rules. As well as I noticed my requests using POSTMAN never send any preflight OPTIONS requests when I initiate a simple GET, POST, etc..

Here are the headers of both an OPTIONS request as well as a GET request to follow it that is returning my error

OPTIONS Request

Remote Address:127.0.0.1:80 
Request URL:http://localhost.api/api/v1/tracks?$filter=id%20eq%20guid%27d7de10ba-e353-455b-a3cb-ced9b4965141%27&
Request Method:OPTIONS
Status Code:200 OK

Request Headers

Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, authorization
Access-Control-Request-Method:GET
Cache-Control:no-cache
Connection:keep-alive
DNT:1
Host:vegas.ine.com
Origin:http://localhost.angular
Pragma:no-cache
Referer:http://localhost.angular/admin/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36   

Response Headers

Access-Control-Allow-Headers:content-type, authorization
Access-Control-Allow-Methods:POST, PUT, GET, DELETE, OPTIONS
Access-Control-Allow-Origin:http://localhost.angular
Cache-Control:no-cache
Connection:close
Content-Type:text/html
Date:Thu, 01 May 2014 16:22:19 GMT
Server:Apache/2.2.26 (Unix) DAV/2 PHP/5.4.24 mod_ssl/2.2.26 OpenSSL/0.9.8y
Set-Cookie:laravel_session=eyJpdiI6IktOZjlTM1ZVNUx0TEhoaTczY3dQcDBKRWlvbnppbDA3QTdqSENJdTc2R1U9IiwidmFsdWUiOiJEZ2ltXC9mNm1Qa20rV3BVRlNHTXgySGtUeVlpNjNZcGFudDFBWDJJekl1MEVNVlhSRE5WWk5YZDNxUkZuU0VEVytcL3NLNlVBXC9hZWtJQzdHU2FqVWtMdz09IiwibWFjIjoiYTYxYjEwNjlmYmI2MjMwNmE4MzlkYjIwNGZlNzA4Y2ViZGVkZmU1MTQzMzc5NmU2YzI2ZGExNzYxY2U5ZjdiMCJ9; expires=Thu, 01-May-2014 18:22:19 GMT; path=/; httponly
X-Frame-Options:SAMEORIGIN
X-Powered-By:PHP/5.4.24  

GET Request

Remote Address:127.0.0.1:80
Request URL:http://localhost.api/api/v1/tracks?$filter=id%20eq%20guid%27d7de10ba-e353-455b-a3cb-ced9b4965141%27&
Request Method:GET
Status Code:302 Found

Request Headers

Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Authorization:Bearer 6Ss4XPrPM5jQD7Es0dz7TPRQ76hGA69vT9K94pst
Cache-Control:no-cache
Connection:keep-alive
DNT:1
Host:vegas.ine.com
Origin:http://localhost.angular
Pragma:no-cache
Referer:http://localhost.angular/admin/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36

Response Headers

Access-Control-Allow-Origin:http://localhost.angular
Cache-Control:no-cache
Connection:Keep-Alive
Content-Type:text/html; charset=UTF-8
Date:Thu, 01 May 2014 16:22:19 GMT
Keep-Alive:timeout=5, max=100
Location:http://localhost.api/session/invalid
Server:Apache/2.2.26 (Unix) DAV/2 PHP/5.4.24 mod_ssl/2.2.26 OpenSSL/0.9.8y
Set-Cookie:laravel_session=eyJpdiI6InlnREVPcUJTcyswMnRLanFDSlZ6QWFBVXZWMGdMNVNLYWxNTHRJVUlkalk9IiwidmFsdWUiOiJ4aXN5U0dcL1NYeGQrcUVzWFhYV3o2MWhcL25hQTlhcVUxbWxkN2R6SG9KZDNKaGNLTkRQY2FyTitpVHNGZzYxVVRtZUhoZGZRWE9GWjZRaDd1VVwvZUZuUT09IiwibWFjIjoiY2EzZTViZGIzZmVlMDcwZjdhMzBjOWQxYTgwZWNlYTJiMDk3ODdlZTk3NTYxMDNmM2YyODJjOGIxMzBmMmJlMiJ9; expires=Thu, 01-May-2014 18:22:20 GMT; path=/; httponly
Transfer-Encoding:chunked
Vary:Authorization
X-Clockwork-Id:1398961340.2239.1349476325
X-Clockwork-Version:1.5
X-Frame-Options:SAMEORIGIN
X-Powered-By:PHP/5.4.24

解决方案

I have done something like this and it worked fine for me

//pattern to allow origins
$allowedOriginPattern = /** YOUR PATTERNS **/;
$allowedOrigin = "";
if (preg_match($allowedOriginPattern, $_SERVER['HTTP_ORIGIN'])) {
    $allowedOrigin = $_SERVER['HTTP_ORIGIN'];
}

/**
 * set http content type
 */
header('Content-Type: application/json;charset=UTF-8');
header('Access-Control-Allow-Origin: ' . $allowedOrigin);
header('Access-Control-Allow-Methods: DELETE, HEAD, GET, OPTIONS, POST, PUT');
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');
header('Access-Control-Max-Age: 1728000');

I have added this code in laravel index.php

Here is the reference for CORS http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0

这篇关于CORS预检后的302重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆