2017-02-25 75 views
1

我正在學習創建Laravel api。我嘗試保護我的數據不受未授權用戶的影響,例如:不允許未經授權的用戶獲取數據並將數據發佈到我的應用程序。在瀏覽器中它工作:如果用戶不提供登錄憑證,他什麼都沒有。在郵遞員中,我可以獲取所有沒有憑據的數據。爲什麼?Laravel API - 郵政局未經授權的用戶無法工作保護

public function __construct() 
{ 
    $this->middleware('auth.basic'); 
    //works in browser but not in postman 
} 

獲取所有的經驗教訓JSON:

public function index() 
{ 
    $lessons = Lesson::all(); 

    return $this->respond([ 
     'data' => $this->transformCollection($lessons->toArray()) 
    ]); 
} 

Post方法:(如果我不給標題和正文的價值觀,我得到了422響應代碼)

public function store() 
{ 
    if (!Input::get('title') or !Input::get('body')){ 
     return $this->setStatusCode(422)->respondWithError("Parameters failed validation"); 
    } 

    Lesson::create(Input::all()); 
    return $this->respondCreated("Successfully created"); 
} 

如何防止郵差從未經授權的用戶獲取和發佈方法。有沒有解決方法?

+0

你也許忘了關在郵遞員的憑據? –

+0

我在哪裏看到它? –

+0

如果我試圖以非授權用戶的身份獲取數據,那麼我不應該得到任何數據 –

回答

4

你應該從郵遞員傳遞令牌並驗證它。 Click here to view how to pass token from postman.

$this->validate($request, [ 
    'token' => 'required', 
]); 

而且隨後

public function index() 
    { 
     $u = UserSession::where('token',$token)->first(); 
     if(count($u) > 0) { 
      $lessons = Lesson::all(); 

      return $this->respond([ 
       'data' => $this->transformCollection($lessons->toArray()) 
      ]); 
     } else { 
      return Api::error(100, $inputs, array("Invalid Token")); 
     } 
    }