I'm building an api to authenticate my users through my mobile application
The login controller return me the correct token.
<?php
namespace App\Api\V1\Controllers;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tymon\JWTAuth\JWTAuth;
use App\Http\Controllers\Controller;
use App\Api\V1\Requests\LoginRequest;
use Tymon\JWTAuth\Exceptions\JWTException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class LoginController extends Controller
{
public function login(LoginRequest $request, JWTAuth $JWTAuth)
{
$credentials = $request->only(['username', 'password']);
try {
$token = $JWTAuth->attempt($credentials);
if(!$token) {
throw new AccessDeniedHttpException();
}
} catch (JWTException $e) {
throw new HttpException(500);
}
return response()
->json([
'status' => 'ok',
'token' => $token
]);
}
}
Postman result
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHBzOlwvXC9iZXRhZmlsZS5vcmdcL2dpcHNcL3B1YmxpY1wvYXBpXC9hdXRoXC9sb2dpbiIsImlhdCI6MTQ5Mjc4MDI2NiwiZXhwIjoxNDkyNzgzODY2LCJuYmYiOjE0OTI3ODAyNjYsImp0aSI6InZHWkxaNHNqRUlqYW05WTMifQ.g8_-qHsVVvCEj9_BoqDCKJ9QHvm-yqWALsXmxeMK_3c"
}
Now when I tried to get the current user by token I get the signature error
User controller
<?php
namespace App\Api\V1\Controllers;
use JWTAuth;
use App\Record;
use App\Http\Requests;
use Illuminate\Http\Request;
use Dingo\Api\Routing\Helpers;
use App\Http\Controllers\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class RecordController extends Controller
{
use Helpers;
public function store(Request $request) {
//$record = new Record;
//return $this->currentUser();
$currentUser = JWTAuth::parseToken()->authenticate();
return $currentUser;
}
private function currentUser() {
return JWTAuth::parseToken()->authenticate();
}
}
Postman result
{
"error": {
"message": "Token Signature could not be verified.",
"status_code": 500
}
}
I already try by pass the token by url domain.com/api/auth?token=token_key and by header Authorization Bearer token_key
Also I have the jwt secret inside config/jwt.php 'secret' => env('jwt_secret') and inside .env JWT_SECRET=jwt_secret
Any tip to help to solve this issue?
Thanks
Try generate a key:
php artisan jwt:secret
This will update your .env file with something like JWT_SECRET=foobar
Related
I created a Laravel login passport API but when email is provided "null" or password is null, it's not showing validation required error. It's returning html of something?
Here is my code of controller:
<?php
namespace App\Http\Controllers\Api;
use\App\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
class AuthController extends Controller
{
public function login(Request $request)
{
$loginData= $request->validate([
'email'=>'required',
'password'=>'required',
]);
if(!auth()->attempt($loginData))
{
return response()->json(['message'=>'Invalid credientails']);
}
$accessToken =auth()->user()->createToken('authToken')->accessToken;
return response()->json(['user'=>auth()->user(),'access_Token'=>$accessToken]);
}
}
Try this
Also please make sure you include the class validator in controller-> use Validator;
$validator = Validator::make($request->all(), [
'email'=>'required',
'password'=>'required',
]);
if ($validator->fails())
{
$message = $validator->errors()->first();
return response()->json(['statusCode'=>200,'success'=>false,'message'=>$message], 200);
}
Hello Guys nowadays am working on laravel api everything is perfect just one issue am facing that is when i write wrong username and password so i am able to get user data but when i enter correct user information so i am getting exception that is invalid credentials. please help me
here is my model code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class email extends Model
{
protected $table = 'users';
}
&
Here is my Controller Code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\email;
class EmailController extends Controller
{
public function databyemail(Request $request){
$data = email::where('email', $request->email)->first();
if($data->password === bcrypt($request->password))
{
return response()->json($data);
}
else
{
return response()->json(['error' => 'Incorrect credentials!']);
}
}
}
Can you try Hash::check method for matching password.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Hash;
use App\email;
class EmailController extends Controller
{
public function databyemail(Request $request){
$data = email::where('email', $request->email)->first();
if( Hash::check( $request->password, $data->password ) ) {
return response()->json($data);
}else{
return response()->json(['error' => 'Incorrect credentials!']);
}
}
}
I am creating user authentication using a custom table. In my login controller authentication is working fine and redirected to dashboard. But when I am going to create another url using a new controller, user auth data not showing for that controller.
I want to get user data through auth facade in constructor. How will that possible?
Here is my code:
web.php:
<!---Routes for login and dashboard-->
Route::get('/login','CustomLogin#index');
Route::post('/login','CustomLogin#checklogin');
Route::get('/','CustomLogin#SuccessLogin');
Route::get('/logout','CustomLogin#logout');
<!---Routes for other controller where user auth not working-->
Route::get('/add-creditor', 'AddCreditor#index');
CustomLogin.php (controller):
<?php
namespace App\Http\Controllers;
use App\library\My_functions;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\User;
use Illuminate\Support\Facades\Auth;
use Redirect;
use View;
use Session;
use Cookie;
class CustomLogin extends Controller
{
public function __construct()
{
$this->_myFun = new My_functions;
}
public function index()
{
if(!Auth::check()) {
return view('CustomLogin.CustomLogin');
}
else{
Redirect::to(SITE_URL)->send();
}
}
public function username()
{
return 'user_name';
}
function checklogin(Request $request)
{
$this->validate($request, [
'input-username' => 'required',
'input-password' => 'required'
]);
$user_data = array(
'user_name' => $request->get('input-username'),
'password' => $request->get('input-password')
);
if(Auth::attempt($user_data)){
return redirect('/');
}
else
{
return back()->with('error','Wrong Login Details');
}
}
function SuccessLogin(){
if (!$this->_myFun->DoLogIn()) {
Redirect::to(SITE_URL.'login')->send();
}
else {
$data=array();
return View::make('include.dashboard',$data);
}
}
function logout(Request $request){
Auth::logout();
return redirect('/login');
}
}
Function DoLogIn() (app/library)
<?php namespace App\library {
use Illuminate\Routing\Controller as BaseController;
use App\library\CreateCrmGuid; // Get custom function
use App\library\FunctionForContact; // Get custom function
use Illuminate\Http\Request;
use Session;
use DB;
use Hash;
use Auth;
use App\User;
class My_functions{
public function DoLogIn()
{
//dd(Auth::user()); /*returns data if run from Login controller but null from Add Creditor controller*/
if(Auth::check())
{
$user_id = Auth::user()->id;
define('authenticated_user_id' ,$user_id);
return true;
}
else
{
return false;
}
}
}
AddCreditor Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Cookie;
use Config;
use App\library\my_functions; // Get custom function
use Redirect;
use DB;
use Session;
class AddCreditor extends Controller
{
protected $_myFun;
function __construct(){
dd(Auth::user()); // this returns null
$this->_myFun = new My_functions;
if (!$this->_myFun->DoLogIn()) {
Redirect::to(SITE_URL.'login')->send();
}
}
}
Add auth Middleware in your routes
Route::middleware(['auth'])->get('/add-creditor', 'AddCreditor#index');
Still, after this, you might not get user data through Auth facade in the controller constructor, But in your Route method i.e. AddCreditor#index you will get the user data either through the following methods
Auth::user();
or
request()->user();
Hi I got problem with my Laravel Rest-API apps, whenever i access localhost:8000/api/login in my Postman its say
(1/1) ReflectionException Class signature does not exist
This is my artisan route:list for api/login
POST | api/login | | App\Http\Controllers\Api\UserController#login | api
This is my api route
<?php
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('oauth/token', '\Laravel\Passport\Http\Controllers\AccessTokenController#issueToken');
Route::group(['namespace' => 'Api'], function () {
Route::post('/login', 'UserController#login');
});
This is my UserController inside Api folder
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\User;
use Response;
class UserController extends Controller
{
public function __construct()
{
$this->content = array();
}
public function login()
{
if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
$user = Auth::user();
$this->content['token'] = $user->createToken('Pizza App')->accessToken;
$status = 200;
} else {
$this->content['error'] = "Unauthorised";
$status = 401;
}
return response()->json($this->content, $status);
}
}
please help me, if I trying to test my Rest-Api in postman, its keep saying
(1/1) ReflectionException
Class signature does not exist
I think you can use a sample for custom authentication in laravel:
https://www.minddevelopmentanddesign.com/blog/add-custom-api-authentication-to-laravel/
I am using Laravel 5.3 My ForgotPasswordController looks like that:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Base\BaseController;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
class ForgotPasswordController extends BaseController
{
use SendsPasswordResetEmails;
public function __construct()
{
$this->middleware('guest');
}
public function showLinkRequestForm()
{
$title = $this->title;
$appName = $this->appName;
$action = $this->action;
return view('password.forgotPassword')->with(compact('title', 'appName', 'action'));
}
}
ResetPasswordController code :
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Base\BaseController;
use Illuminate\Foundation\Auth\ResetsPasswords;
class ResetPasswordController extends BaseController
{
use ResetsPasswords;
public function __construct()
{
$this->middleware('guest');
}
public function showResetForm(Request $request, $token = null)
{
return view('passwords.resetPassword')->with(
['token' => $token, 'email' => $request->email]
);
}
public function reset(Request $request)
{
$this->validate($request, [
'token' => 'required',
'password' => 'required|confirmed|min:6',
]);
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$response = $this->broker()->reset(
$this->credentials($request), function ($user, $password) {
$this->resetPassword($user, $password);
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
return $response == Password::PASSWORD_RESET
? $this->sendResetResponse($response)
: $this->sendResetFailedResponse($request, $response);
}
}
My Admin Route :
Route::group(['namespace' => 'Auth'], function() {
Route::get('/forgotpassword/reset', 'ForgotPasswordController#showLinkRequestForm');
Route::post('/forgotpassword/email', 'ForgotPasswordController#sendResetLinkEmail');
Route::get('/password/reset/{token}', 'ResetPasswordController#showResetForm');
Route::post('/password/reset', 'ResetPasswordController#reset');
});
BaseController Code :
<?php
namespace App\Http\Controllers\Base;
use App\Http\Controllers\Controller;
class BaseController extends Controller
{
protected $appName = 'Stackoverflow';
protected $title = 'Welcome to Stackoverflow';
protected $action;
}
I can send the link to my email, but once I click the link/button.
It throws an error like above. Any idea ?
You are not using the required namespace, try to use the following in your controller:
use Illuminate\Http\Request;
You are getting the error due to the fact that your script tries to load the Request class from the current namespace :App\Http\Controllers\Auth
Request docs for Laravel 5.3