Using Nginx Proxy to support WeChat Web site authorization of different domain names

Source: Internet
Author: User
Tags oauth sprintf
This article mainly introduces the use of Nginx Proxy support page authorization of different domain names, has a certain reference value, now share to everyone, the need for friends can refer to

admitted a bit to the title party. This development of a project encountered problems, before there are two old projects based on yaf , domain name for m.baidu.com (do example), and then the page authorization domain name is filled m.baidu.com , and the new development of the project is based on laravel , then the domain name for wechat.baidu.com , but the page authorization domain name How to do, this is the pit dad. Of course, most people will not encounter such a painful thing.

Premise

Laravel5.5php7.1.0nginx1.10overtrue/laravel-wechat

Understanding OAuth

This process has to be understood

Thanks for the pictures of the Super God

From the process we can see that the callback url domain name is actually our website authorization domain name. So now that we can make a fake,
In the domain name for wechat.baidu.com The project, we also put the page authorization domain name written m.baidu.com , and then use nginx to do agent, based on location forwarding to wechat.baidu.com the next;

Rewriting overtrue/laravel-wechat Middleware

Why rewrite this middleware, because the middleware will directly get your domain name, so if I use wechat.baidu.com , then the default will be callback after the jump to wechat.baidu.com , and actually I want to jump m.baidu.com to

MiddlewareCreate a new middleware under the folder OAuthAuthenticate and inherit 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 functio  N Handle ($request, \closure $next, $account = ' Default ', $scopes = null) {//$account with $scopes write reverse case (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-&gt ; Oauth->user ()??                []]);                $isNewSession = true;                Event::fire (New Wechatuserauthorized (Session ($sessionKey), $isNewSession, $account));            Return Redirect ()->to ($this->gettargeturl ($request));            } session ()->forget ($sessionKey); Local and test environments use this if (app::environment () = = ' Local ' | | App::environment () = = "Test") {return $officialAccount->oauth->scopes ($scopes)->redirect ($request-&G            T;fullurl ());            } $query = $request->getquerystring (); $question = $request->getbaseurl (). $request->getpathinfo () = = '/'?            '/?' : '?'; $url = $query? $request->getpathinfo (). $question.$query: $request->getpathinfo (); $url = "http://m.baidu.com". $url;        This step is important. Return $officialAccount->oauth->scopes ($scopes)->redirect ($url);        } event::fire (New wechatuserauthorized (Session ($sessionKey), $isNewSession, $account));    Return $next ($request); }   }

Then in kernel.php the $routeMiddleware add

"Wechat.oauth.baidu.com" =>oauthauthenticate::class

Then it can be used in the routing file and finished.

Nginx Setup Agent

this feels nothing good to say, in fact the principle is very simple, directly on the code
     Under m.baidu.com domain name configuration, set the location rule, all router start with/official_account wechat.baidu.com, and then set the cross-domain 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 days #add_header ' Content-type ' text/html charset=utf-8 ';                #add_header ' content-length ' 0;        return 200;        The following is the backend server to be proxied, they do not need to modify the code to support cross-domain 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; }

This Code configuration Reference "Nginx configuration implementation Cors", but directly copied over, with the proxy_pass 400 request header or cookie too large error, Baidu a bit "400 Bad Request Request Header Or Cookie Too Large" , <<nginx configuration reverse proxy or jump appear 400 problem processing records >> can be resolved, Is the following three settings have a problem, get rid of just fine:

         Proxy_set_header Host $host;           Proxy_set_header x-real-ip $remote _addr;         Proxy_set_header x-forwarded-for $proxy _add_x_forwarded_for;

Comprehensive analysis, should be nginx used proxy_pass when the jump, if the direct use of the domain name, and the need to submit the current access to the IP address, the nginx cause of the bug death cycle, do not know if you have encountered this situation.

And then restart it, and finish.

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.