Giter Club home page Giter Club logo

Comments (1)

Articus avatar Articus commented on August 26, 2024

Hi,
Personally I just add specific attribute with high priority to handlers or handler methods that require authentication. This attribute reads token from request headers, validates and decrypts it, calls some service to retrieve user information and "attributes" request with this info.
If any stage fails, attribute can just throw Articus\PathHandler\Exception\Unauthorized for 401 response or Articus\PathHandler\Exception\Forbidden for 403 response.
Here is short sample of such attribute:

namespace IdentityServer;

use Articus\PathHandler\Attribute\AttributeInterface;
use Articus\PathHandler\Exception as PAException;
use Psr\Http\Message\ServerRequestInterface as Request;

class Attribute implements AttributeInterface
{
	const AUTHORIZATION_HEADER_RE = '/^Bearer (?<token>[a-zA-Z0-9\._\-]+)$/';
	const USER_INFO_ATTR = 'userInfo';
	/**
	 * TODO any service that can validate authentication token and provide information about authenticated user
	 * @var Client\UserInfo
	 */
	protected $userInfoClient;
	/**
	 * Attribute constructor.
	 * @param Client\UserInfo $userInfoClient
	 */
	public function __construct(Client\UserInfo $userInfoClient)
	{
		$this->userInfoClient = $userInfoClient;
	}

	public function __invoke(Request $request)
	{
		$authorizationHeaders = $request->getHeader('Authorization');
		if (empty($authorizationHeaders) || empty($authorizationHeaders[0]))
		{
			throw new PAException\Unauthorized('Empty authorization header');
		}
		$matches = [];
		if (preg_match(self::AUTHORIZATION_HEADER_RE, $authorizationHeaders[0], $matches) < 1)
		{
			throw new PAException\Unauthorized('Malformed authorization header');
		}
		$userInfo = null;
		try
		{
			$userInfo = $this->userInfoClient->get($matches['token']);//TODO or any other logic to validate and decrypt token
		}
		catch (\Exception $e)
		{
			throw new PAException\Unauthorized('Invalid authorization header', $e);
		}
		$request = $request->withAttribute(self::USER_INFO_ATTR, $userInfo);
		return $request;
	}
}

And even shorter sample of handler that uses this attribute:

namespace App\Handler;

use Articus\PathHandler\Operation;
use Articus\PathHandler\Annotation as PHA;
use Articus\PathHandler\Producer as PHProducer;
use Psr\Http\Message\ServerRequestInterface;
use IdentityServer as IS;

class Test implements Operation\GetInterface
{
	/**
	 * @PHA\Attribute(priority=10, name=IS\Attribute::class)
	 * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/json")
	 * @return mixed
	 */
	public function handleGet(ServerRequestInterface $request)
	{
		$userInfo = $request->getAttribute(IS\Attribute::USER_INFO_ATTR);
		//TODO use this user info somehow in handler or in anotehr attribute with lower priority
	}
}

Authorization can be handled in the same manner. For example you can pass user roles required to access method via attribute options (check Articus\PathHandler\Attribute\Factory for sample how to get them):

/**
 * @PHA\Attribute(priority=10, name="AuthorizationAttribute", options={
 *     "requiredRoles": {"admin"},
 * })
 * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":"SomeClass","objectAttr":"test"})
 * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/json")
 */
public function handlePatch(ServerRequestInterface $request)
{
}

Hope that will help)

from pathhandler.

Related Issues (3)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.