Passing the token of an Angularjs controller to an Laravel API

Asked

Viewed 257 times

1

I am trying to pass the token that I have my controller to authenticate into an API in Laravel. However I am encountering the error:

"token_not_provided"

Note: I am using the Jwtauth with Laravel 5.4

Follow my API:

use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\PessoaRequest;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Facades\JWTAuth;

class PessoaController extends Controller
{

protected $user;

    public function __construct(\Illuminate\Http\Request $request)
{
    $header = $request->header('Authorization');

    return response([
        'status' => 'success'
    ]) ->header('Authorization', $header);
}

Angular Controller:

(function() {
 app.controller('MemberController', [
'$scope', '$rootScope', 'AppConfig', '$http',
function($scope, $rootScope, AppConfig, $http) {
  var vm = this;
  $rootScope.page.title = 'SEC BASE';

  $rootScope.authenticated = true;
  $scope.token = $rootScope.user.remember_token;
   getMembers();

    // Obtem a listagem de todos os usuarios
  function getMembers() {
    $scope.token = $rootScope.user.remember_token;
    Loading.show();
    $http({
      method: 'GET',
      url: AppConfig.ApiUrl + 'members',
   headers: {
            'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8',
            'Accept': 'application/json',
            'Authorization ' : 'Bearer' + $scope.token,
      }
    }).then( response => {
      // console.log(response);
      $scope.members = response.data;
    }).finally(Loading.hide)
      .catch(function(err) {
            console.log(err);
        });
  }
  ]);
})();

Handler.php:

use Exception;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Tymon\JWTAuth\Facades\JWTAuth;
public function render($request, Exception $exception)
{
    // detect instance
    try {
        $user = JWTAuth::parseToken()->authenticate();
    } catch (Exception $e) {
        if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
            return $this->respondWithError("Token is Invalid");
        }else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
            return $this->respondWithError(['error'=>'Token is Expired']);
        }else{
            return $this->respondWithError(['error'=>'Something is wrong']);
        }
    }
    return $next($request);
}
  • Apparently you are not sending the token in the request, I suggest you add a "Authorization" header and send the token as value to this header

  • I even adjusted it, I forgot to edit the question.

  • Adds a .catch at the end of .then, prints error and displays here, maybe it helps

  • Correct the question again.

2 answers

1

I think the problem is that the Bearer is "glued" to token needs a space in the middle.

'Authorization ' : 'Bearer' + $scope.token,

Corrected:

'Authorization' : 'Bearer ' + $scope.token,

0

In PHP:

use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request as Request;
use App\User;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\PessoaRequest;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Facades\JWTAuth;

class PessoaController extends Controller
{

    protected $user;

    public function __construct(Request $request)
    {
        $data = $request->all();

        $parametro = $data['campo'];

        return response([
            'resultado' => $parametro,
            'status' => 'success'
        ]) ->header('Authorization', $header);
    }
}

In the route file of the api.php:

Route::get('url-da-sua-api', ['before' => 'jwt-auth', function() {

    $user = JWTAuth::parseToken()->toUser();
    return Response::json(compact('user'));
}]);

In the javascript of Angularjs:

function getMembers() {
    Loading.show();

var request = $http({
                     method: "get",
                     url: AppConfig.ApiUrl + 'members',
                     data: {campo: "parametro"},
                     headers:{
                        'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8',
                        'Accept': 'application/json',
                        'Authorization' : 'Bearer ' + $rootScope.user.remember_token,
                       }
                    });

                    return request.then( _handleSuccess, _handleFail );
}

function _handleFail(response) {
  Loading.hide();
  console.log(response);
}

function _handleSuccess(response) {
  if($http.pendingRequests.length === 0){
      Loading.hide();
  }
   return response.data;
}

getMembers()
 .then(function(result) {
    if (result.status) {
       $scope.sua_saida = result.resultado;
       console.log(result);
    }
})
 .catch(function(e){
   console.log(e);
});

Gives a peek here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.