1

I am using Laravel 5.1 to retrieve data from an api and display it in a website.

The api returns the auth user every time I send any request with a JWT token in the header.

When the user has signed in once, I send the token in every request.

I want a way in which I can check auth user and its details in every view.

1) How do I set the response to the User class so that I can use it later in the views as a Facade?

2) How do I retrieve the auth user?

3) How do check if there is a auth user or not?

A response is in Json

  "feed": {...}
  "auth": {
    "id": 1,
    "name": "Hetu Nandu",
    "title": "Student",
    "kp": 43,

  }

1 Answer 1

1

A call to Auth::user() returns currently authenticated user. As you want to re-use existing authentication functionality with a remote user storage you'll need to do a couple of things.

First, you'll need a User class that will be used for authentication. It needs to implement Authenticatable interface. The only method from this interface you need is getAuthIdentifier() - it should return unique identifier of given user. This identifier is saved in session and later used to reload used data for subsequent requests. You could return the JWT token.

Next, you need to authenticate a user in Laravel. You can do it with

Auth::login($user)

This will store user's identifier in session.

Finally, you need a way to load user data for subsequent requests. You'll need to implement custom user provider - it's fairly simple. You can find an example in the docs: https://laravel.com/docs/5.1/authentication#adding-custom-authentication-drivers

Sign up to request clarification or add additional context in comments.

5 Comments

So the $user passed in the method will be the token?
<?php namespace App; use Illuminate\Auth\Authenticatable; class User { use Authenticatable; public function getAuthIdentifier() { return Request::cookie('token'); } }
It needs to be the user object.
So I am able to log user in with Auth::login($user) but i am still having issues with the userprovider. If i am right, this class will pull the data from the response and suply it to auth class right? which method should i use for my case? I am feeling like a real noob here :|
Doesnt the API you use provide some client library? If not have a look at guzzle library

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.