iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 27
0
Modern Web

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

Day#27 在json_login驗證傳來的資料及將回傳的格式改為IRI

上一篇提到建立簡單的json_login ,那如果今天從前端送過來的不是json格式怎麼辦!!!?


在前端利用catch抓取錯誤訊息回傳錯誤json格式的error,
後端我們可以透過自己寫驗證來去判斷它的Content-Type Header 是不是json格式

json_login 都叫json_login了,當然是只給格式為json的時候使用R

  /**
     * @Route("/login",name="app_login",methods={"POST"})
     */
    public function login(){

        if (!$this->isGranted('IS_AUTHENTICATED_FULLY')) {
            return $this->json([
                'error' => 'Invalid login request: check that the Content-Type header is "application/json".'
            ], 400);
        }


        return $this->json([
            'user' => $this->getUser()? $this->getUser()->getId():null,
        ]);
    }

現在我們回傳的是登入者的id,那假設如果我想要拿到所有的登入者資訊,而且是以IRI的方式呈現呢?

  1. 先傳入一個Interface => IriConverterInterface ,這名字很明顯就是IRI轉換的介面(ゝ∀・)

     /**
         * @Route("/login",name="app_login",methods={"POST"})
         */
        public function login(IriConverterInterface $iriConverter){
    
            if (!$this->isGranted('IS_AUTHENTICATED_FULLY')) {
                return $this->json([
                    'error' => 'Invalid login request: check that the Content-Type header is "application/json".'
                ], 400);
            }
    
    
             return $this->json([
                'user' => $this->getUser()? $this->getUser()->getId():null,
            ]);
        }
    
  2. 接著回傳一個Response

     /**
         * @Route("/login",name="app_login",methods={"POST"})
         */
        public function login(IriConverterInterface $iriConverter){
    
            if (!$this->isGranted('IS_AUTHENTICATED_FULLY')) {
                return $this->json([
                    'error' => 'Invalid login request: check that the Content-Type header is "application/json".'
                ], 400);
            }
    
    
            return new Response(null,204,[
    
                'Location' =>  $iriConverter->getIriFromItem($this->getUser())
            ]);
        }
    

Response 第一個參數為要回應的內容, 第二個參數為http回應碼,
我們可以自己給200 or 201 ,204 只要是成功的代碼都可以,
第三個參數是放header設定的地方 , 也就是我們在header Location的參數設定將我們的物件轉成IRI格式

這篇來個簡單的划水 ,
下一篇會簡單提到 SameSite Cookie的設定及 Csrf attach 也就是我們熟悉的(跨站請求偽造)

第29天會提到建立簡單的Api test ,

所以下一篇除了介紹上述兩種東西外,還會做Api test的前置作業( º﹃º )


上一篇
Day#26 Security設定檔裡設定Json_login
下一篇
Day#28 Cookie & SameSite Cookie 和 安裝API test 前置作業
系列文
PHP框架-Symfony4 + api platform 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言