使用nginx代理,支持微信网页授权不同域名

承认有点标题党了。这次开发一个项目遇到问题,以前有两个微信老项目基于
yaf,域名为
m.baidu.com(做示例),然后网页授权域名填的是
m.baidu.com,而这次新开发的项目是基于
laravel,那么域名为
wechat.baidu.com,但是网页授权域名怎么办,这就坑爹了。当然了,大部分人不会遇到这么蛋疼的事情吧。

前提

laravel5.5

php7.1.0

nginx1.10

overtrue/laravel-wechat

了解微信OAuth

这个过程必须要明白
《使用nginx代理,支持微信网页授权不同域名》

感谢超神的图片
《使用nginx代理,支持微信网页授权不同域名》

从流程我们可以看到,回调url域名其实就是我们的网页授权域名。那么既然这样我们是不是可以造个假呢,
在域名为wechat.baidu.com的项目下,我们也把网页授权域名写成m.baidu.com,然后再使用nginx做代理,基于location 转发到wechat.baidu.com下;

改写overtrue/laravel-wechat中间件

为什么要改写这个中间件呢,因为中间件默认会直接获取你的域名,所以如果我使用
wechat.baidu.com,那么默认就会回调后跳转到
wechat.baidu.com,而实际上我要跳转到
m.baidu.com

Middleware文件夹下新建一个中间件OAuthAuthenticate,并且继承 Overtrue\LaravelWeChat\Middleware\OAuthAuthenticate;:



namespace App\Http\Middleware;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Event;
use Overtrue\LaravelWeChat\Events\WeChatUserAuthorized;
use Overtrue\LaravelWeChat\Middleware\OAuthAuthenticate as BaseAuthenticate;

class OAuthAuthenticate extends BaseAuthenticate
{
   
   
    public function handle($request, \Closure $next, $account = 'default', $scopes = null)
    {
        // $account 与 $scopes 写反的情况
        if (is_array($scopes) || (\is_string($account) && str_is('snsapi_*', $account))) {
            list($account, $scopes) = [$scopes, $account];
            $account || $account = 'default';
        }

        $isNewSession = false;
        $sessionKey = \sprintf('wechat.oauth_user.%s', $account);
        $config = config(\sprintf('wechat.official_account.%s', $account), []);
        $officialAccount = app(\sprintf('wechat.official_account.%s', $account));
        $scopes = $scopes ?: array_get($config, 'oauth.scopes', ['snsapi_base']);

        if (is_string($scopes)) {
            $scopes = array_map('trim', explode(',', $scopes));
        }

        $session = session($sessionKey, []);

        if (!$session) {
            if ($request->has('code')) {
                session([$sessionKey => $officialAccount->oauth->user() ?? []]);
                $isNewSession = true;

                Event::fire(new WeChatUserAuthorized(session($sessionKey), $isNewSession, $account));

                return redirect()->to($this->getTargetUrl($request));
            }

            session()->forget($sessionKey);




            //本地和测试环境下使用这个
            if(App::environment()=='local' ||App::environment()=="test"){
                return $officialAccount->oauth->scopes($scopes)->redirect($request->fullUrl());
            }


            $query = $request->getQueryString();

            $question = $request->getBaseUrl().$request->getPathInfo() == '/' ? '/?' : '?';

            $url= $query ? $request->getPathInfo().$question.$query : $request->getPathInfo();

            $url="http://m.baidu.com".$url; //就这一步很重要
            
            return $officialAccount->oauth->scopes($scopes)->redirect($url);
        }

        Event::fire(new WeChatUserAuthorized(session($sessionKey), $isNewSession, $account));

        return $next($request);
    }

   
}

然后在kernel.php中的$routeMiddleware添加

"wechat.oauth.baidu.com"=>OAuthAuthenticate::class

然后就可以在路由文件使用了,完工。

nginx 设置代理

这个觉得没有什么好讲的,其实原理很简单,直接上代码

     //在m.baidu.com域名配置下,设置location规则,所有router以/official_account开头的都去wechat.baidu.com下,然后设置跨域
     
     location /official_account/{
        add_header 'Access-Control-Allow-Origin' "$http_origin";
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,X-CSRF-TOKEN,X-XSRF-TOKEN';
        add_header 'Access-Control-Allow-Credentials' 'true';
        if ($request_method = 'OPTIONS') {
                add_header 'Access-Control-Allow-Origin' "$http_origin";
                add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
                add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,X-CSRF-TOKEN,X-XSRF-TOKEN';
                add_header 'Access-Control-Allow-Credentials' 'true';
                #add_header 'Access-Control-Max-Age' 1728000; # 20 天
                #add_header 'Content-Type' 'text/html charset=UTF-8';
                #add_header 'Content-Length' 0;
                return 200;
        }
    # 这下面是要被代理的后端服务器,它们就不需要修改代码来支持跨域了
        proxy_pass http://wechat.m.liaorusanshe.com;
        #       proxy_set_header Host $host;  
        proxy_redirect off;
        #proxy_set_header X-Real-IP $remote_addr; 
        #proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_connect_timeout 60;
        proxy_read_timeout 60;
        proxy_send_timeout 60;


    }

这个代码配置参考了《Nginx配置实现CORS》,但是直接复制过来,配合proxy_pass会出现400 request header or cookie too large错误, 百度了一下"400 Bad Request Request Header Or Cookie Too Large",<<nginx配置反向代理或跳转出现400问题处理记录>>可以解决,就是如下三个设置有问题,去掉就好了:

         proxy_set_header Host $host;  
         proxy_set_header X-Real-IP $remote_addr; 
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

综合分析,应该是nginx在使用proxy_pass做跳转时,如果直接使用域名,且需要向后端提交当前访问的IP地址时,引发nginxbug造成死循环,不知道大家有没有遇到过这种情况。

然后重新启动就好了,完工。

    原文作者:soledad
    原文地址: https://segmentfault.com/a/1190000015183759
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞