laravel-auth-token icon indicating copy to clipboard operation
laravel-auth-token copied to clipboard

Authentication Support for dingo api

Open dennisoderwald opened this issue 10 years ago • 5 comments

Hi,

we want to use dingo, but the AuthProvider must to be adjusted. Is this possible?

https://github.com/dingo/api/wiki/Authentication

dennisoderwald avatar Jun 27 '14 18:06 dennisoderwald

+1

adosaiguas avatar Jul 25 '14 05:07 adosaiguas

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 avatar Aug 07 '14 00:08 adosaiguas

@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.

tappleby avatar Aug 14 '14 10:08 tappleby

:+1:

lucasmichot avatar Aug 20 '14 08:08 lucasmichot

:+1:

simplenotezy avatar Oct 25 '14 19:10 simplenotezy