Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OAuth2 advice #1

Closed
BradCrumb opened this issue Aug 6, 2017 · 1 comment
Closed

OAuth2 advice #1

BradCrumb opened this issue Aug 6, 2017 · 1 comment
Labels

Comments

@BradCrumb
Copy link

Hi there,

I really like this library and have used it many times in combination with Swagger.

Now I have to create a public api with authentication for certain endpoints. Normally in Zend Expressive I put a extra Middleware to the specific route but with PathHandler I cannot implement this. Can you give me some advice to implement this with PathHandler?

For example I want to put a Middleware to validate the tokens for a specific endpoints: /products/ .

@Articus
Copy link
Owner

Articus commented Aug 7, 2017

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants