I want to created a REST API where only the login user can access it
$app->get(‘/Info/{input}’, function ($request, $response, $args) {
if(Security()->isLoggedIn()){
}
}
I call the API with JWT header
And I want to check whether the user is login or not
Security()->isLoggedIn() is not working and
global $Security;
$Security->isLoggedIn() is also not working
How can I check the user is login or not in the REST API
Make sure you add your API action by the Api_Action event (not Route_Action event) and you call your API by the route “/api/Info/xxx”, otherwise your handler is not called.
Yes I have added the API under → function Api_Action($app){ }
the API call also working
$app->get(‘/Info/{input}’, function ($request, $response, $args) {
$input = $args[“input”] ?? null;
$result = array(“InputData”=>$input);
$response = $response->write(json_encode($result));
return $response;
}
I can call the above API by “/api/Info/xxx”
And it can be access by everyone.
But I want to give access to this api action “Info” only to the api with the header JWT token.
In my custom code how can i check that the user is login or the api has a valid JWT token.
if(JWT Token is valid){
return ----
}
else return ----
From the source code, if the JWT header is valid, the JWT middleware will login the user. If Security()->isLoggedIn() return false, that means there is not valid JWT header or the user is not valid. You may debug by checking, e.g. var_dump(Security()).
On the API Calling script I have add the “Bearer” as
CURLOPT_HTTPHEADER => array(
“X-Authorization: Bearer $jwttoken”,
“content-type: application/json”
),
But still I am unable to access the REST API with Security
on the REST API I try as
$result[“userlevel”] = CurrentUserLevel();
$response = $response->write(json_encode($result));
return $response;
And is there any other option to access the API by token which is unique to every user.
On the Authentication Table we will increase a field with “token” and the user token will be store.
By using this token the user can access the API
eg.
/api/gfjurulj14sgfh2434–MYTOKEN/Info/xxx"