2018-10-18

使用 localhost 測試 Facebook login

2018-10 開始 Facebook login 強制使用 HTTPS 了,若要在 localhost 測試也是得用 HTTPS 才行。以下的參考連結說明 MAMP 的作法:
https://gist.github.com/jfloff/5138826

Facebook login 以前做過幾次,都是針對活動網站的,這次也不例外。一陣子沒做了,想說依照官方範例,應該不會有太大問題,但結果還是卡了一兩個小時。以下列出卡到的點:

1. 在設定 Facebook app 時,在「設定」〉「基本資料」,「應用程式網域」和「網站網址」的域名請一致。(設定介面經常在變,規則也是)

2. 在「Facebook 登入」〉「設定」裡,「對重新導向 URI 使用 Strict 模式」現在預設是設定為開啟,而且不能變更。所以一定要在「有效的 OAuth 重新導向 URI」填寫正確的 redirect uri。

3. 使用 facebook/graph-sdk 時,可以直接 copy sample code 去改,但記得在 login.php 和 fb-callback.php 裡都要先以 session_start() 啟動 session 功能。因為 FacebookRedirectLoginHelper 的 CSRF 是寫在 session 裡的。



在 MAMP localhost 上使用自簽的 https

參考
https://gist.github.com/jfloff/5138826

  1. Backup your /Applications/MAMP/conf/ dir.
  2. Generate a (dummy) SSL Certificate
    $ cd ~
    
    # generate a private key (will request a password twice)
    $ openssl genrsa -des3 -out server.key 1024
     
    # generate certificate signing request (same password as above)
    $ openssl req -new -key server.key -out server.csr
     
    # Answer the questions
    Country Name (2 letter code) [AU]: CA
    State or Province Name (full name) [Some-State]: Quebec
    Locality Name (eg, city) []: Montreal
    Organization Name (eg, company) [Internet Widgits Pty Ltd]: Your Company
    Organizational Unit Name (eg, section) []: Development
    Common Name (eg, YOUR name) []: localhost
    Email Address []: your_email@domain.com
    A challenge password []: # leave this empty
    An optional company name []: # leave this empty
     
    # generate the certificate
    $ openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
     
    # remove the password from the server key
    $ cp server.key server.tmp
    $ openssl rsa -in server.tmp -out server.key
     
    # Move the certificate into your MAMP apache configuration folder
    $ cp server.crt /Applications/MAMP/conf/apache
    $ cp server.key /Applications/MAMP/conf/apache
    
  3. Open /Applications/MAMP/conf/apache/httpd.conf and uncomment Include /Applications/MAMP/conf/apache/extra/httpd-ssl.conf.
  4. Keep your vhost in /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf just the same.
  5. In /Applications/MAMP/conf/apache/extra/httpd-ssl.conf, find the following block and edit the fields Server Name and Document Root with the values you already have in your vhost.
    #   General setup for the virtual host
    DocumentRoot "/Applications/MAMP/Library/htdocs"
    ServerName www.example.com:443
    ServerAdmin you@example.com
    ErrorLog "/Applications/MAMP/Library/logs/error_log"
    TransferLog "/Applications/MAMP/Library/logs/access_log"
    and edit in your DocumentRoot and ServerName settings:

FB 留言