Zend expressive 3 + OAuth2 Server + Authentication

Hello guys!

I’m developing a middleware for a system I’m trying to put to run.

As I am still starting in Zend Expressive, this week I had a difficulty in the authentication part, I could not find anything documented regarding my question and I went to Slack of the project, where I was helped by one of the colleagues that indicated an example of configuration file no git.

As I did not find any answer I decided to post here a workaround of how I solved the difficulty.

First of all, I will present the authentication workflow.

The OAuth2 server worked correctly, too.

The problem was when I inserted the pipe for the authentication, which caused Expressive to request a token even when I made the request requesting the token.

So the way I solved the problem was:

Before the pipe that calls RouteMiddleware, I include the following pipe:
$app-> pipe (’/auth’, Zend\Expressive\Authentication\OAuth2\OAuth2Middleware::class);

So instead of creating this route in my routes.php I created only this pipe that runs only for this route, and the other routes are treated conventionally with their respective middlewares.

I hope it helps someone else who has the same problem as me.

[]s.

@RodriAndreotti If you still have this problem (sorry for the late response), you should whitelist the routes that do not need authentication (e.g. the login page). In the OAuth2Middleware you should check if the user has identity or the route is in the whitelistied routes.

e.g. if (empty($session->get(UserIdentity::class)) && !in_array($currentRoute, $whiteListedRoutes)) {
//redirect to login page or response with code 405
}

I used the session as storage, but you can use what storage you want.

Also, supposing that OAuth2Middleware checks the identity, you should edit the pipe and add this middleware for the routes where the user needs to be authenticated.

e.g. $app-> pipe (’/api’, Zend\Expressive\Authentication\OAuth2\OAuth2Middleware::class);

1 Like

Hey, dude!
Thanks, for reply!

I have solved this calling a pipe pointing to:
$app-> pipe (’/auth’, Zend\Expressive\Authentication\OAuth2\OAuth2Middleware::class);

Before RouteMiddleware.

But it’s nice to have another solution.

Thanks a lot!

1 Like