Comments (2)
I've gotten back to digging into this and I think it might be possible to use a rule or something, since the __invoke method required by the RuleInterface actually takes ServerRequestInterface ...? It seems like undocumented functionality though
This all seems rather flimsy to me though -- still unclear how I would first authenticate the user and then get the API method to check against their permissions. Maybe I'll have to drop this library or something but I feel like there's an obvious answer I'm missing here since being able to check if a user has permissions to access a particular route beyond a hardcoded set of credentials/paths should be elementary.
from slim-basic-auth.
I figured out an easier way to do it without using this library (sorry!)
I'm putting it here to save anyone else the time.
Here's a stripped down version that checks for basic auth and such, Slim 4 of course.
<?php
use YourApp\AuthMiddleware;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Routing\RouteContext;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
class AuthMiddleware implements MiddlewareInterface {
/**
* @var ResponseFactoryInterface
*/
private $responseFactory;
/**
* @param ResponseFactoryInterface $responseFactory
*/
public function __construct(ResponseFactoryInterface $responseFactory) {
$this->responseFactory = $responseFactory;
}
/**
* @inheritDoc
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
$failure = $this->responseFactory->createResponse();
$failure->getBody()->write('Authorization denied');
$failure = $failure->withStatus(401);
if (!isset($_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"])) {
// auth not provided
return $failure->withAddedHeader("X-Debug", "auth not provided");
}
$username = $_SERVER["PHP_AUTH_USER"];
$password = $_SERVER["PHP_AUTH_PW"];
// do your auth stuff here
$auth_condition_that_should_be_true = true;
$user = [ "id" => 1 ]; // whatever data or object you need
if (!$auth_condition_that_should_be_true) {
// user doesn't exist
return $failure->withAddedHeader("X-Debug", "user doesn't exist");
}
// now we can check that the user has permission
$routeContext = RouteContext::fromRequest($request);
$route = $routeContext->getRoute();
$the_route = $route->getPattern(); // /foo/bar/baz
$the_user_has_permission_for_route = true;
if (!$the_user_has_permission_for_route) {
// user doesn't have permission
return $failure->withAddedHeader("X-Debug", "no permission for action");
}
// load the user so it's accessible in the request handler
$newRequest = $request->withAttribute("user", $user);
// Keep processing middleware queue as normal
return $handler->handle($newRequest);
}
}
And you can then do this:
<?php
// ... composer and whatever else ...
use YourApp\AuthMiddleware;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use Slim\Psr7\Response;
$app = AppFactory::create();
$app->addMiddleware(new AuthMiddleware($app->getResponseFactory()));
$app->addRoutingMiddleware();
$app->get('/your/api/path', function (Request $request, Response $response, $args) {
// you can get your user stuff here
$user = $request->getAttribute("user");
$result["user"] = [
"id" => $user->getId(),
"username" => $user->getUsername(),
];
$response->getBody()->write(json_encode($result, JSON_PRETTY_PRINT));
return $response;
});
$app->run();
from slim-basic-auth.
Related Issues (20)
- Access user/passwd from Authenticator within Slim route handler HOT 1
- Specify callback for the relaxed configuration parameter HOT 3
- Authenticator misinterpretation of "authorization" header HOT 5
- Ignore is not working as expected
- Uncaught Error: Interface 'Psr\Http\Message\ResponseFactoryInterface' not found HOT 2
- HTTP_X_FORWARDED_PROTO HOT 1
- ignore list HOT 1
- After/Before Callbacks never called? HOT 3
- Class 'Tuupola\Middleware\HttpBasicAuthentication' not found HOT 32
- 401 error in postman HOT 3
- Interface ResponseFactoryInterface not found HOT 5
- Authentification error HOT 4
- Connecting over HTTP when I should not be able to HOT 1
- "final class" and CloudFlare proxification error HOT 1
- Why does local(HTTP) connection work but not online(HTTPS)? HOT 16
- Add request object back to the error handler. HOT 3
- Allow using any callable as a rule
- Do not assume callbacks are a closure
- Before & After Callbacks Never Triggered
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from slim-basic-auth.