I used jwt-auth.
It works well in login, but when I try to register it and go through the login request the error below occurred.
"message": "Unauthenticated."
Here is the source code:
config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => True,
],
routes/api.php:
Route::group([
'middleware' => 'api',
'namespace' => 'App\Http\Controllers',//must include the path
'prefix' => 'auth'
], function ($router) {
Route::post('login', 'AuthController@login');
Route::post('signup', 'AuthController@signup');
Route::post('logout', 'AuthController@logout');
Route::post('refresh', 'AuthController@refresh');
Route::post('me', 'AuthController@me');
});
AuthController.php
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login,signup']]);
}
public function login()
{
$credentials = request(['email', 'password']);
if (! $token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
public function signup(Request $request){
$validation = $request->validate([
'email' =>'required',
'name' =>'required',
'password'=>'required|min:6|confirmed',
]);
$data = array();
$data['name'] = $request->name;
$data['email'] = $request->email;
$data['password'] = Hash::make($request->password);
DB::table('users')->insert($data);
return $this->login($request);
}
I provided DB and Hash classes. In postman, I put the route in the POST method and set headers Accept
and content-type
as application/json
formate and in the body part, I set x-www-form
and input all the keys and values with confirmation_password key. It not inserting into the database and showing the error message. I tried it by clearing the config cache and route cache. I also tried it with raw and json format.
CodePudding user response:
i think you problem with ur constractor middleware u didn't make the except value right u have to make to different values for except like that
$this->middleware('auth:api', ['except' => ['login','signup']]);
CodePudding user response:
Better use create or save Method to store the new user. After you store user in your database you can generate a usertoken and send him back. And the user is logged in. Every further request is then regulated via the token.
$token = // generate an new token with the JWT toker Helper method ;
return response()->json([
'status' => 'ok',
'token' => $token,
'user' => $user
], 201);