Hope you are doing well. ;)
However, I m facing problems while generating JWT Auth Token
we have a custom user table called somename_users where email field called email_id and we used md5 hash to store the password (don't judge). So first I tried to do some tests and it worked, I was successfully generated JWT auth token, so after that, I'm trying to implement it on our dev server.
App\Model\User.php
<?php
namespace App\Model;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
const CREATED_AT = 'created_at';
const UPDATED_AT = 'modified_at';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'first_name','middle_name','last_name','email_id','password',[...]
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password'
];
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* @return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* @return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
App\Http\Controllers\api\v1\TestController.php*
namespace App\Http\Controllers\api\v1;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use JWTAuth;
use App\Model\User;
class TestController extends Controller
{
// public function get(){
// return User::all();
// }
// public function login(Request $request)
// {
// $creds = array();
// $creds["email_id"] = $request->email_id;
// $creds["password"] = md5($request->password);
// try {
// if (! $token = JWTAuth::attempt($creds)) {
// return response()->json(['error' => 'invalid_credentials','token'=>$token], 400);
// }
// } catch (JWTException $e) {
// return response()->json(['error' => 'could_not_create_token'], 500);
// }
// return response()->json(compact('token'));
// }
// /**
// * Get the token array structure.
// *
// * @param string $token
// *
// * @return \Illuminate\Http\JsonResponse
// */
// protected function respondWithToken($token)
// {
// return response()->json([
// 'access_token' => $token,
// 'token_type' => 'bearer',
// 'expires_in' => auth()->factory()->getTTL()
// ]);
// }
/**
* Create a new AuthController instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login']]);
}
/**
* Get a JWT via given credentials.
*
* @return \Illuminate\Http\JsonResponse
*/
public function login(Request $request)
{
$creds = array();
$creds["email_id"] = $request->email_id;
$creds["password"] = md5($request->password);
$creds = array();
$creds["email_id"] = $request->email_id;
$creds["password"] = md5($request->password);
if (! $token = auth()->attempt($creds)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
/**
* Get the authenticated User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth()->user());
}
/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth()->refresh());
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
}
Config/auth.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
//original
'users' => [
'driver' => 'eloquent',
'model' => App\Model\User::class,
//'table' => 'users',
],
// 'users' => [
// 'driver' => 'eloquent',
// 'model' => App\Model\User::class,
// ],
/*'users' => [
'driver' => 'eloquent',
'table' => 'users',
],*/
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
//original
/*'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],*/
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];
Every time I try to hit the API endpoint of login with email and password I got unauthorized response, but credentials are absolutely perfect.
Please help me.
Thanks in advance
laravel login attempt for password working with bcrypt
instead of md5
, so your code must be changed.
TestController.php
public function __construct()
{
...
$this->guard = "api"; // add
}
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'email_id' => 'required|string',
'password' => 'required|string',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
$user = \App\User::where([
'email_id' => $request->email_id,
'password' => md5($request->password)
])->first();
if (! $user ) return response()->json([ 'email_id' => ['Unauthorized'] ], 401);
if (! $token = auth( $this->guard )->login( $user ) ) {
return response()->json([ 'email_id' => ['Unauthorized'] ], 401);
}
return $this->respondWithToken($token);
}