Reputation: 1221
I am learning to create Laravel api. I try to protect my data from not authorized users like: do not permit unauthorized users to get and post data to my app. In the browser it works: If the user does not provide login credentials he does not get anything. In postman I can get all the data without credentials. Why?
public function __construct()
{
$this->middleware('auth.basic');
//works in browser but not in postman
}
Get all the lessons as JSON:
public function index()
{
$lessons = Lesson::all();
return $this->respond([
'data' => $this->transformCollection($lessons->toArray())
]);
}
Post method: (if I don't give title and body values, I get the 422 response code)
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");
}
How can I prevent Postman from get and post methods for unauthorized users. Is there a workaround for this?
Upvotes: 2
Views: 1267
Reputation: 1554
You should pass token from postman and validate it. Click here to view how to pass token from postman.
$this->validate($request, [
'token' => 'required',
]);
And Then
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"));
}
}
Upvotes: 4