iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 26
0
Modern Web

PHP框架-Symfony4 + api platform 系列 第 26

Day#26 Security設定檔裡設定Json_login

  • 分享至 

  • xImage
  •  

登入驗證除了可以自己寫以外,還可以在security.yaml裡做json_login的設定


首先,我們要先到security.yaml設定json_login

security:
    encoders:
        App\Entity\User:
            algorithm: auto

    providers:
        app_user_provider:
            entity:
                class: App\Entity\User
                property: email
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: true

            json_login:
                check_path: /api/login
                username_path: email
                password_path: password

    access_control:

在firewalls下有看到json_login嗎!?

第一個參數代表的是,我們login所要執行的action , 可以使用uri 或是 action 的別名

第二個參數代表的是我們要驗證的帳號欄位

第三個參數代表的是我們要驗證的密碼欄位

設定完成後,我們要在src下建立一個資料夾名為Controller,
並在裡面建立一個專門給Security用的Controller,
什麼意思是專門給Security用的~?
就是這個Controller要盡量保持乾淨 , 只放登入登出或是登入登出驗證相關的function

這個Controller 跟一般的一樣 ,要繼承AbstractController

class SecurityController extends AbstractController
{
    /**
     * @Route("/api/login", name="login", methods={"POST"})
     */
    public function login()
    {
		return $this->json([
            'user' => $this->getUser() ? $this->getUser()->getId() : null]
        );
    }

}

這邊先單純的判斷登入成功回傳登入者的Id,如果不是的話回傳null,
下一篇會提到要怎麼樣驗證是不是json格式及如何將回傳的Response變成IRI的格式

以上是登入的action , 如果是登出的話,一樣要到security.yaml裡做設定 ,但只要設定action位置就好

security:
    encoders:
        App\Entity\User:
            algorithm: auto

    providers:
        app_user_provider:
            entity:
                class: App\Entity\User
                property: email
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: true

            json_login:
                check_path: /api/login
                username_path: email
                password_path: password

            logout:
                path: logout

    access_control:

在json_login 下加上一個logout並且給予 action 的URI或別名

接著一樣在剛剛建立的SecurityController裡在建立一個logout function

class SecurityController extends AbstractController
{
    /**
     * @Route("/login", name="app_login", methods={"POST"})
     */
    public function login()
    {
       
        return $this->json([
            'user' => $this->getUser() ? $this->getUser()->getId() : null]
        );
    }

    /**
     * @Route("/logout", name="logout")
     */
    public function logout()
    {
        throw new \Exception('should not be reached');
    }
}

這樣一來,我們就生完最最最初版的json login了 ,
下一篇開始我們要來幫它加上驗證 , 把它回傳格式改造成IRI 了ԅ(¯﹃¯ԅ)


上一篇
Day#25 被匯出匯入跟編碼搞到快崩潰的小菜鳥(`д´)-切割字串與計算字元長度
下一篇
Day#27 在json_login驗證傳來的資料及將回傳的格式改為IRI
系列文
PHP框架-Symfony4 + api platform 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言