laravel-auth-token
laravel-auth-token copied to clipboard
Authentication Support for dingo api
Hi,
we want to use dingo, but the AuthProvider must to be adjusted. Is this possible?
https://github.com/dingo/api/wiki/Authentication
+1
This is what I did to integrate this library into Dingo\Api:
- Followed the instructions to install this module
- Created an authentication provider helper class for Dingo\Api:
<?php
use Dingo\Api\Auth\Provider;
use Illuminate\Http\Request;
use Illuminate\Routing\Route;
use Tappleby\AuthToken\AuthTokenManager;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
class AuthTokenAuthenticationProvider extends Provider {
/**
* AuthToken authentication manager.
*
* @var \Tappleby\AuthToken\AuthTokenManager
*/
protected $auth;
/**
* Create a new AuthTokenAuthenticationProvider instance.
*
* @param \Tappleby\AuthToken\AuthTokenManager $auth
* @return void
*/
public function __construct(AuthTokenManager $auth)
{
$this->auth = $auth;
}
protected function getAuthToken($request) {
$token = $request->header('X-Auth-Token');
if(empty($token)) {
$token = $request->input('auth_token');
}
return $token;
}
/**
* Authenticate request with Auth Token.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Routing\Route $route
* @return mixed
*/
public function authenticate(Request $request, Route $route)
{
$token = $this->getAuthToken($request);
$driver = $this->auth->driver();
$user = $driver->validate($token);
if (!$user) {
throw new UnauthorizedHttpException('AuthToken', 'Invalid authentication credentials.');
}
return $user;
}
/**
* Get the providers authorization method.
*
* @return string
*/
public function getAuthorizationMethod()
{
return 'auth_token';
}
}
- Changed Dingo\Api config to accept the new authentication provider:
'auth' => [
'custom' => function ($app) {
return new \AuthTokenAuthenticationProvider($app['tappleby.auth.token']);
}
],
And that's it, I can now protect my REST services using auth tokens, just setting protected = true
, in the Dingo\Api route config.
@adosaiguas this looks like a great solution. I'm on vacation right now but when I get back I will add a note about your solution to the readme.
:+1:
:+1: