0
votes

In my project i am using laravel and nuxt with laravel passport.

For some reason laravel passport always returns the message 'unauthorized' when i try to register a user.

In api.php I created a route that references to the create function in my authcontroller:

Route::post('create', 'AuthController@create');

This is my Authcontroller:

namespace App\Http\Controllers\API;

use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AuthController extends Controller
{
    public function local()
    {
        return response()->json(['user' => auth()->user()]);
    }

    public function oauth()
    {
        return response()->json(auth()->user());
    }

    public function create(request $request){

        $validatedData = $request->validate([
            'name' => 'required|max:12',
            'email' => 'required|email|unique:users',
            'password' => 'required|confirmed'
        ]);        

        $user = User::create($validatedData);

        $accesToken = $user->createToken('authToken')->accessToken;     

        return response()->json([
            'user' => $user,
            'access_token' => $accessToken
        ]);
    }
}

In postman i try to register a user with some data,

I am making a post request to 127.0.0.1:8000/api/create

In the Headers tab i have a key, accept with the value application/json In the body of my request i send the following data as form-data:

  • name = testuser
  • email = [email protected]
  • password = secret
  • password_confirmation = secret

But somehow i always get the message unauthorized... I am sure this is the right URI. I think this problem has something to do with laravel passport but cant seem to figure out why i am being redirected. When i remove the accept key from my header in postman i am simply being redirected to the login page of laravel. I think that somehow somewhere in passport all routes require authorization...

If someone has a solution or usefull information that would be great! :)

1

1 Answers

0
votes

Maybe you could try to get token from URL /oauth/token and use it as bearer token on your create request. I think that the Api middleware expects to receive a token.

Header example:

'headers' => [
    'Accept' => 'application/json',
    'Authorization' => 'Bearer '.$accessToken, //From route /oauth/token
],