Skip to content

Commit 5e5ccf3

Browse files
committed
new: develop api with bearer token
1 parent ac4821c commit 5e5ccf3

File tree

6 files changed

+174
-15
lines changed

6 files changed

+174
-15
lines changed

app/Http/Controllers/Api/UserApiController.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,4 +41,18 @@ public function index($request, $response)
4141
];
4242
return $response->json($data);
4343
}
44+
45+
public function user($request, $response)
46+
{
47+
$req = $request->all();
48+
$data = [
49+
'success' => true,
50+
'user' => [
51+
'id' => $req->id,
52+
'name' => 'John Doe',
53+
'email' => ''
54+
]
55+
];
56+
return $response->json($data);
57+
}
4458
}

app/Http/Middlewares/AuthApi.php

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<?php
2+
3+
namespace LaraCore\App\Http\Middlewares;
4+
5+
class AuthApiMiddleware
6+
{
7+
public static function handle($request)
8+
{
9+
// Get the API token from the request headers
10+
$token = $request->getHeader('Authorization');
11+
12+
// Check if the token is present
13+
if (!$token) {
14+
self::unauthorizedResponse();
15+
}
16+
17+
// Validate the token (you may want to implement a more secure validation mechanism)
18+
$isValidToken = self::validateToken($token);
19+
20+
if (!$isValidToken) {
21+
self::unauthorizedResponse();
22+
}
23+
24+
// The token is valid, continue with the request
25+
}
26+
27+
private static function unauthorizedResponse()
28+
{
29+
// Handle unauthorized access (e.g., return a 401 Unauthorized response)
30+
header('HTTP/1.0 401 Unauthorized');
31+
echo 'Unauthorized';
32+
exit;
33+
}
34+
35+
private static function validateToken($token)
36+
{
37+
// Validate the token against your storage (e.g., database)
38+
// Return true if the token is valid, false otherwise
39+
// Implement this method based on your specific authentication mechanism
40+
41+
// For demonstration purposes, we'll assume a simple token validation
42+
$validTokens = [
43+
'eW91ci1hcGktdG9rZW4=',
44+
]; // Store valid tokens securely
45+
46+
return in_array($token, $validTokens);
47+
}
48+
}

config/Config.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,23 @@
3434
'csrf' => [
3535
'key' => 'csrf_token'
3636
],
37+
/**
38+
* Set API token
39+
* condition: true | false
40+
* key: base64_encode('laracore-api-token')
41+
* if condition is true then you need to pass api token in header
42+
* Authorization: Bearer base64_encode('laracore-api-token')
43+
* and set check to true
44+
* it's will set api token for all api routes
45+
* if you want to set api token for specific route then set check to false
46+
* and pass api token in header
47+
* and create middleware for that route
48+
* and set middleware in route
49+
*/
50+
'api-token' => [
51+
'check' => false,
52+
'key' => 'bGFyYWNvcmUtYXBpLXRva2Vu'
53+
],
3754
'remember' => [
3855
'cookie_name' => 'hash',
3956
'cookie_expiry' => 604800

framework/Request.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ public function __construct()
1515
{
1616

1717

18+
1819
}
1920

2021
/**
@@ -197,6 +198,34 @@ public function getParam($key)
197198
return $this->routeParams[$key];
198199
}
199200

201+
/**
202+
* @method for check http authorization
203+
*
204+
* @return bool
205+
*/
206+
public function isHttpAuthorizedOrFail()
207+
{
208+
return isset($_SERVER['HTTP_AUTHORIZATION']) && !empty($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : false;
209+
}
210+
211+
/**
212+
* @medium for set json header
213+
*
214+
* @return void
215+
*/
216+
public function setJsonHeader()
217+
{
218+
header('Content-Type: application/json');
219+
}
220+
221+
/**
222+
* @method for setUnauthorized
223+
*/
224+
public function setUnauthorizedHeader()
225+
{
226+
header('HTTP/1.0 401 Unauthorized');
227+
}
228+
200229
/**
201230
*
202231
*/

framework/Routers/Router.php

Lines changed: 61 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace LaraCore\Framework\Routers;
44

55
use LaraCore\App\Http\Kernel;
6+
use LaraCore\Framework\Configuration;
67
use LaraCore\Framework\Request;
78
use LaraCore\Framework\Response;
89

@@ -16,7 +17,7 @@ class Router
1617
/**
1718
* @var array
1819
*/
19-
protected $middleware = [];
20+
protected $middlewares = [];
2021

2122
/**
2223
* @var array
@@ -80,15 +81,29 @@ public function middleware($middleware)
8081
/**
8182
* Method to set middleware group
8283
*
83-
* @param string $middlewareGroup
84+
* @param string $middleware
8485
*/
8586
public static function middlewareGroup($middleware, callable $callback)
8687
{
8788
$request = new Request();
8889
$middlewareAliases = Kernel::$middlewareAliases;
8990
$middleware = $middlewareAliases[$middleware];
91+
92+
/** @var mixed */
93+
$previousMiddleware = self::$middlewares;
94+
self::$middlewares = [];
95+
9096
call_user_func($callback);
9197
self::runMiddleware($request, $middleware);
98+
99+
// Assign the current middleware to the routes in the group
100+
// $groupMiddleware = self::$middlewares;
101+
// self::$middlewares = $previousMiddleware;
102+
103+
// foreach (self::$routes as &$route) {
104+
// $route['middleware'] = array_merge($route['middleware'], $groupMiddleware);
105+
// }
106+
92107
}
93108

94109
/**
@@ -180,9 +195,9 @@ private static function executeRoute($request, $response, $route)
180195
{
181196
$callback = $route['action'];
182197

183-
// set api header
198+
// set api header of api route
184199
if ($route['isApi']) {
185-
self::setApiHeader();
200+
self::setApiHeaderWithAuth($request, $response);
186201
}
187202

188203
if (is_array($callback)) {
@@ -281,22 +296,54 @@ public static function setApiPrefix($prefix)
281296
*
282297
* @return void
283298
*/
284-
public static function setApiHeader()
299+
public static function setApiHeaderWithAuth($request, $response)
285300
{
301+
// Enable CORS (Cross-Origin Resource Sharing)
286302
header('Access-Control-Allow-Origin: *');
287303
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
288304
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
289-
header('Content-Type: application/json');
290-
}
291305

292-
/**
293-
* set api header, cors, content type with auth token
294-
*
295-
* @return void
296-
*/
297-
public static function setApiHeaderWithAuth()
298-
{
306+
// Set content type to JSON
307+
$request->setJsonHeader();
308+
309+
$config = Configuration::get('api-token');
310+
if (!$config['check']) {
311+
return;
312+
}
299313

314+
// Check for Authorization header (Bearer token)
315+
$authHeader = $request->isHttpAuthorizedOrFail();
316+
317+
if (!$authHeader) {
318+
// No Authorization header provided
319+
$request->setUnauthorizedHeader();
320+
$response->jsonResponse(
321+
['error' => 'No Authorization header provided'],
322+
401
323+
);
324+
}
325+
// Validate and extract the Bearer token
326+
list($bearer, $token) = explode(' ', $authHeader);
327+
if (empty($token) || strtolower($bearer) !== 'bearer') {
328+
// Invalid or missing Bearer token
329+
$request->setUnauthorizedHeader();
330+
$response->jsonResponse(
331+
['error' => 'Invalid or missing Bearer token'],
332+
401
333+
);
334+
}
335+
// For demonstration, assume a hardcoded valid token
336+
$yourValidAuthToken = $config['key']; // api_token
337+
338+
if ($token !== $yourValidAuthToken) {
339+
// Invalid token
340+
$request->setUnauthorizedHeader();
341+
// echo json_encode(['error'=> VarDumper::dumpAsString($token))
342+
$response->jsonResponse(
343+
['error' => 'Invalid token'],
344+
401
345+
);
346+
}
300347
}
301348

302349
/**

routes/api.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,8 @@
55

66
// Router::setApiPrefix('api');
77

8-
Router::get('/user', [UserApiController::class, 'index']);
8+
// Router::middlewareGroup('authApi', function () {
9+
// Router::get('/user', [UserApiController::class, 'index']);
10+
// });
11+
Router::get('/user', [UserApiController::class, 'index']);
12+
Router::get('/user/{id}', [UserApiController::class, 'user']);

0 commit comments

Comments
 (0)