Lumen JWT send token with requests - laravel

Authentication is working, I have a few routes under auth middleware, Whenever i request it throws :
{
"message": "Failed to authenticate because of bad credentials or an invalid authorization header.",
"status_code": 401
}
How can i send the token with the request like :
Authorization bearer {{Long token}}
It works with `postman`, How can i send the token with request header, Or in any other best way.
Route :
$api->get('/categories', [
'uses' => 'App\Http\Controllers\CategoryController#index',
'as' => 'api.categories',
]);
Method :
public function index() {
$lessons = \App\Category::all();
$token = JWTAuth::getToken(); // $token have jwt token
return response()->json([
'data' => $lessons,
'code' => 200,
]);
}

The question was pretty vague to answer. Please be more specific from next time. From your comments i could finally realise that you want to consume the api from a mobile app.
You need to return the token generated for an user either during login or during registration or any other authentication method/route you have. The mobile app needs to read this response and store the token locally. Then the app needs to inject this token in the request header for every single request. That's the normal api token workflow.
The app should also be coded to read the error response from requests and if it returns errors for expired or invalid token, the app needs to clear the locally stored token and then request the user to login again to generate a fresh token.

you can use : https://github.com/tymondesigns/jwt-auth
requriment :
Laravel 4 or 5 (see compatibility table)
PHP 5.4 +
Steps:
1 : add below line in composer.json in require array
"tymon/jwt-auth": "0.5.*"
2 : run "composer update" in your terminal
3 : after this you have to register service provider
go to config/app.php
and add 'Tymon\JWTAuth\Providers\JWTAuthServiceProvider' this in provider array
and 'JWTAuth' => 'Tymon\JWTAuth\Facades\JWTAuth' , 'JWTFactory' => 'Tymon\JWTAuth\Facades\JWTFactory' this to aliases array
4 : publish pacakge :
"php artisan vendor:publis --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"
5 : generate secrate key in config file
'php artisan jwt:generate'
6 : for addition configuration : https://github.com/tymondesigns/jwt-auth/wiki/Configuration
Usage :
AuthenticateController.php
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
class AuthenticateController extends Controller
{
public function authenticate(Request $request)
{
// grab credentials from the request
$credentials = $request->only('email', 'password');
try {
// attempt to verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
// all good so return the token
return response()->json(compact('token'));
}
}
You can also skip user authentication and just pass in a User object. e.g.
// grab some user
$user = User::first();
$token = JWTAuth::fromUser($user);
The above two methods also have a second parameter where you can pass an array of custom claims. e.g.
$customClaims = ['foo' => 'bar', 'baz' => 'bob'];
JWTAuth::attempt($credentials, $customClaims);
// or
JWTAuth::fromUser($user, $customClaims);
create token based on anything
$customClaims = ['foo' => 'bar', 'baz' => 'bob'];
$payload = JWTFactory::make($customClaims);
$token = JWTAuth::encode($payload);
d

Related

Create session on consuming login with api on laravel

I have an api that has a method to start and I am calling it from a frontend project.
In the front end project I use Guzzle to make the call via post to the api and login, from which I get back a json with the user data and a jwt token.
But when I receive the token as I manage the session, I must create a session and save the token, since the laravel to authenticate I need a model user and have a database, which of course I do not have in this backend because I call the api to log in, which brings a token and user data, then as I manage it from the backend, I'm a little lost there.
$api = new Api();
$response = $api->loginapi(['user'=>'wings#test.com','password'=>'123']);
Because here I could not do Auth::login($user) to generate the session.
Because I don't have here the database because the login is done from the api.
There I call the api, of which the answer is the token, but how do I manage it from here, creating a session? saving the token?
thanks for your help.
With api, you don't usually manage a session. usually, you'd call something like
Auth::attempt([
'email' => 'me#example.com',
'password' => 'myPassword'
]);
If the credentials are correct, laravel will include a Set-Cookie header in response, and, that is how you authenticate with api. Via an auth cookie. You don't need to do anything else.
Let's show you how:
//AuthController.php
public function login(Request $request) {
$validatedData = $request->validate([
'email' => 'required|email',
'password' => 'required'
]);
if(Auth::attempt($validatedData)){
return ['success' => 'true'];
}
else{
return ['success' => false, 'message' => 'Email or password Invalid'];
}
}
public function currentUser (){
return Auth::user();
}
Now, the APi file
Route::post('/login', ['App\Http\Controllers\AuthController', 'login']);
Route::get('/current_user', ['App\Http\Controllers\AuthController', 'currentUser']);
Now if you make a call to /api/current_user initially, you'll get null response since you're not currently logged in. But once you make request to /api/login and you get a successful response, you are now logged in. Now if you go to /api/current_user, you should see that you're already logged in.
Important ::
If you are using fetch, you need to include credentials if you're using something other than fetch, check out how to use credentials with that library or api
You want to use the API to authenticate and then use the SessionGuard to create session including the remember_me handling.
This is the default login controller endpoint for logging in. You don't want to change this, as it makes sure that user's do not have endless login attempts (protects for brut-force attacks) and redirects to your current location.
public function login(Request $request)
{
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if (method_exists($this, 'hasTooManyLoginAttempts') &&
$this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
if ($request->hasSession()) {
$request->session()->put('auth.password_confirmed_at', time());
}
return $this->sendLoginResponse($request);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
The core happens when we try to "attemptLogin" at
protected function attemptLogin(Request $request)
{
return $this->guard()->attempt(
$this->credentials($request), $request->boolean('remember')
);
}
When using the SessioGurad (which is default) the method attemptLogin fires a couple of events, checks if the user has valid credentials (by hashing the password and matching it with db) and then logs the user in, including the remember me functionality.
Now, if you don't care about events, you can just check from your API if the credentials match and then use the login method from the guard. This will also handle the remember me functionality. Something like this:
protected function attemptLogin(Request $request)
{
$username = $request->input($this->username());
$password = $request->input('password');
$result = \Illuminate\Support\Facades\Http::post(env('YOUR_API_DOMAIN') . '/api/v0/login' , [
'username' => $username,
'password' => $password
])->json();
if(empty($result['success'])){
return false;
}
// Maybe you need to create the user here if the login is for the first time?
$user = User::where('username', '=', $username)->first();
$this->guard()->login(
$user, $request->boolean('remember')
);
return true;
}

Login with only email in Lumen (JWT Auth)

I want to make the password optional while login into the system. If the user enters the password the login works fine and return the jwt token, when I entered to try to login only with email it gives the following error:-
Undefined index: password (500 Internal Server Error)
The following is the code of my login method
public function authenticateUser($request)
{
$input = $request->only('email','password');
if (!$authorized = Auth::attempt($input, true)) {
return $this->failure('Credentials doesnot match our records!', 401);
} else {
$token = $this->respondWithToken($authorized);
return $this->success('Login Successfully !', $token, 200);
}
}
protected function respondWithToken($token)
{
return [
'token' => $token,
'token_type' => 'Bearer',
'expires_in' => Auth::factory()->getTTL() * 60,
'user' => Auth::user()
];
}
so basically, what I want is when a user enters an email it will login and should return the token, and if the user login with email and password then it should also work and return the token.
You can create a custom Authentication User Provider that will work around this potentially missing 'password' field. Though, I would probably not here. You can check the input yourself to see if there is a password or not. If there is pass it through attempt like normal. If it is not there find the user using the configured User Provider and login to the guard (what attempt is doing).
Perhaps something like this:
public function authenticateUser($request)
{
if ($request->has('password')) {
$token = Auth::attempt($request->only(['email', 'password']));
} else {
$token = ($user = Auth::getProvider()->retrieveByCredentials($request->only(['email'])))
? Auth::login($user)
: false;
}
return $token
? $this->success('Login Successfully !', $this->respondWithToken($token), 200)
: $this->failure('Credentials do not match our records!', 401);
}
The error that you're getting means that there is no password key in the input array that you're sending via request. This happens on this line:
$input = $request->only('email','password');
In order to bypass that, you would need go get all inputs, or check if those inputs exist and then read from them:
//Get all inputs
$input = $request->input();
//Or get email first, and then check for password
$input['email'] = $request->email;
$input['password'] = $request->filled('password') ? $request->password : null;
Note: Since I can't see your actual login functions, this might not work with only email, since password might be required parameter. If that's the case, you will have to alter those functions.

Get user data using passport access token - Laravel

I've been trying to return user data using access token but keep getting error:
Invalid payload
My method was to get the token then find the user id from oauth_access_tokens table. My code is as follows:
public function authenticateUser($token){
$user_id = DB::table('oauth_access_tokens')->where('id', trim($token))->value('user_id');
$user = \App\User::find($user_id);
Auth::login($user, true);
}
The token is something like this:
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjkyZGU3ZGYyMDcxZjgzMzU5YWUxMmRlYzM4ZGJiM2EyMTk0NzEyYTQ5NmRiNzgwZWJkMDg2Yjc0NThkZjU0NmFlZmU2Yzg0N2Q0Mjc5MDAxIn0.eyJhdWQiOiIxIiwianRpIjoiOTJkZTdkZjIwNzFmODMzNTlhZTEyZGVjMzhkYmIzYTIxOTQ3MTJhNDk2ZGI3ODBlYmQwODZiNzQ1OGRmNTQ2YWVmZTZjODQ3ZDQyNzkwMDEiLCJpYXQiOjE1NzczNzE4MDYsIm5iZiI6MTU3NzM3MTgwNiwiZXhwIjoxNjA4OTk0MjA1LCJzdWIiOiIzMCIsInNjb3BlcyI6W119.Io4xkJYEczbI7rhFD_UKAoe7v_1-RLJXjA6XqGIe2nRAWEgMkg-mokQUiGz41xYVazmDmACDwwYSRr-iTTzwc591NABfxsmMk7OdYkUKb93UTA3JhKClEGSP82y1QrIfm9XTZ0KKDaCKlfKqye1Aobj9zFthQdApegTaK61ReLQa7MzO6EM5fcZ3udsLL3QpKXFuyO6JcPKRauKIbA8oNIKEdadprLWJSeQieIyA8lpYOr453QzgZGgzCwPY1U2RmIbCzqyNQD_L5264-ix1503KxgPt4F_Cl82WXm7tNsZKNwE-vGKhCc2CcgAgTV1lIj7ItDf2KpDh_Jt96Uiv2eJ3OtXYvuOTErz9mNnQ1T38hxQmKDh8XlG3f7JgIWWzN6m8ItBV1KyGZi0-vn2HXetkZTNIyfJV8E5-RaGUzIKX7RejWd5BVaqFw0OjDYPeliVOaZzfcZCRnPDSJBGwf7YqJrRXP61LMasn_ZJ-i8G5JIaQx2vdmfYgE41O5F9fE5uEF5-mIV979RbnswL6CJsSGmmUMzC7mPhqL6HtPu2hMTnfHbKY0-efqtzZ5I2TBQU6ODM37RFN5TEljoEgBFG6kAImkGDy4QFH5uqt6V7-ZFxvrKQzQozgezSgA6ITF1sRb7yWfI-9rF7sYE_aKu3r1_KRr4UJLoZqFyvGPP0
Isn't it the token that I should pass to the function above. When I pass it to base64_decode, I see the JSON object along with other gibberish. What am I doing wrong here?
I have never used Laravel Passport before, but I would imagine that the user is already authenticated when using the token. So maybe a route like:
Route::get('/user', function(Request $request) {
return Auth::user();
})->middleware('auth:api');
I've reached to way to do so eventually by sending a request to the api in the other machine while adding the token in the header:
public function authenticateUser($token) {
$client = new \GuzzleHttp\Client();
try {
$response = $client->request('GET', env('APP_API_URL') . '/api/v2/user_data', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token,
],
]);
$request = (string) $response->getBody();
$request = json_decode($request);
$user = User::where('email', $request->data->user->email)->first();
Auth::login($user, true);
} catch (RequestException $e) {
dd('Something went wrong while connection to the api');
}
}

How to add status in default response passport

I am developing and application in web as well as App. For App's API I have use Passport in laravel. Using passport i can create token and using that token I verify user for other api access. But if token in invalid then it return Error message like "Unauthorized" without any status. Can any one tell me what to do if i want to add error status like 401 with message "Unauthorized" . Where I have to change in code so that my web code is not affect. I want json response like below with 2 fields in json.
status:401
message:Unauthorized
You could create a new exception handler middleware to catch these requests and modify the response it returns.
Example:
class oAuthExceptionHandler {
public function handle($request, Closure $next) {
try {
$response = $next($request);
if (isset($response->exception) && $response->exception) {
throw $response->exception;
}
return $response;
} catch (\Exception $e) {
return response()->json(array(
'result' => 0,
'msg' => $e->getMessage(),
), 401);
}
}
}
Then, in your app/Http/Kernel.php, name your middleware and add it into your api group:
protected $routeMiddleware = [
'oauth_exception' => oAuthExceptionHandler::class,
...
];
protected $middlewareGroups = [
...
'api' => [
'oauth_exception',
...
],
];
You can handle the api exception and format its response in app/Exceptions/Handler.php.
Here is the link that you can follow
Laravel API, how to properly handle errors

Laravel - authenticating with session token

Upon login, I return the user object + session token in JSON form, so that the mobile device that connects to my application can be authenticated.
However, I have a difficulty understanding how would I go about authenticating the user only with his session id?
Once logged in, the mobile device sends the session token upon every request, which means I somehow need to check whether it's the same user (using a custom auth filter).
How would I do it?
You may have a table for saving tokens
Add a filter in routes.php
Route::group(array('before' => 'auth'), function() { ... })
And in the filters.php you can search the token in the database, if isn't exist you return a no access response
Route::filter('auth', function () {
$input_token = Input::get('token');
if (!empty($input_token)) {
$validator = Validator::make(
['token' => $input_token],
['token' => 'token']
);
if (!$validator->fails()) {
$token = Token::where('hash', $input_token)->first();
if ($token) {
$user = User::find($token->user_id);
if ($user) {
Auth::login($user);
return;
}
}
}
}
$response = Response::make(json_encode([
'error' => true,
'messages' => [
Lang::get('errors.NO_ACCESS')
]
]), 200);
$response->header('Content-Type', 'application/json');
return $response;
});
You could do it like this:
$sessionID = '4842e441673747d0ce8b809fc5d1d06883fde3af'; // get this from \Session::getId(); from your previous authenticated request (after logging in because it changes).
$s = new \Illuminate\Session\Store(NULL, \Session::getHandler(), $sessionID);
$s->start();
$userID = $s->get('login_82e5d2c56bdd0811318f0cf078b78bfc');
\Session::set('login_82e5d2c56bdd0811318f0cf078b78bfc', $userID);
return \Auth::user();
Not the prettiest code but it works. It creates an instance of a session using the previous Session ID, then start loads it up from file. The user ID is in that key, so then it just sets the user id on the current session. Then when you call Auth::user() it loads up the User using that user id.
The reason for all the numbers in the key is because the larval developer thought it would be smart to hash the Auth class name to make the key as unique as possible... :-S

Resources