How to get id from refresh token in Laravel Passport? - php

I am writing a controller in which I would like to get the refresh token id but I just cannot figure out how to do it in laravel.
There are no problems with decrypting the access token. I am using standard protocol and receive data using the public key of the passport.
i tried different ways.
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class RefreshTokenController extends Controller
{
public static $public_key;
public static function refresh_token(Request $request)
{
self::$public_key = file_get_contents(storage_path() . DIRECTORY_SEPARATOR . 'oauth-public.key');
$refresh_token = $request->get('refresh_token');
$data = base64_decode($refresh_token);
$public_key = openssl_get_publickey(self::$public_key);
openssl_public_decrypt($data, $decrypted, $public_key);
dd($decrypted);
}
}
I tried also standard decrypt();. But it gives an error too.
Example of incoming data.
def50200dc11ab81fdb16530806530f85fe41f7facc934447589b3a0daa202d56f5b4a8265db94b418e09280bcc8a05c88c3817612200d3c28de15c9adfd4a213f7cb136fca6f78099d686fce8d5ddf93f9bb29c1df081d7f7b75394875b5287a7ca5d9ca5eb513ea13a26195aeda41c897832467ec1b0348cdb3e5ed9476e5e7d8712b8628c18ee8ffb525de965faeb3f25b1a8eb4ee904a15341650fe6d3ed901600beda0f80c71b9b607f3e549ba8fbd9eda0e02fc7647ab8b4ea9161f7eb65833bfe46fb7f3e116a207282f947660ead392dc78ad2b9501331b4d28433a421a4193484e113baf8050d3878bd94b6ac860a1a766e79877f1af8d3ab5aee3779bf33c2a7e347552e51bb8b5448585435ef7b79d06853bcd775ce781b8d2e56289dbc8d4a10ec507aecde19bb496e90f88a687ee9bb33755046d50f860f7723d87bd4c079cd4d1242903bdb3ca447ce6ab03f2fd800182d0d8c5a3b7de5402ba2ecb4058d458cbee94da433635877e63120d6418e51eafdfd763191fceef399c16c088e27da9ffbf9
according to oauth_refresh_tokens table. All refresh token IDs are preserved. When calling the refresh token method, according to the refresh token, the corresponding access token matches in the database and is renewed.
I will be grateful for solutions.

<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Defuse\Crypto\Crypto;
use Exception;
use Illuminate\Http\Request;
class RefreshTokenController extends Controller
{
public static function refresh_token(Request $request)
{
$refresh_token = $request->get('refresh_token');
$app_key = env('APP_KEY');
$enc_key = base64_decode(substr($app_key, 7));
try {
$crypto = Crypto::decryptWithPassword($refresh_token, $enc_key);
} catch (Exception $exception){
return $exception;
}
return json_decode($crypto, true);
}
}
Laravel Passport encrypts the password using the APP_ located in the ENV file.
Using the library Defuse\Crypto\Crypto;

Related

Restful API. Cannot add data from Android app to MySQL database using Laravel

I am trying to add data from android app to mysql database using
RxJava and Laravel for RestFul API. I was not able to add data to the database, I think my php code is not correct. Below is my some code for POST method.
StudentController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Student;
use Illuminate\Support\Facades\DB;
class StudentController extends Controller
{
function addData(Request $req) {
$st = new Student;
$st->name = $req->name;
$st->age = $req->age;
if ($st->save()) {
echo "Add 1 field success !";
}
}
}
JsonApi.kt
package com.example.demo9
import io.reactivex.Observable
import retrofit2.Response
import retrofit2.http.*
interface JsonApi {
// For laravel
#FormUrlEncoded
#POST("add2")
fun insertStudent(#Field("name") name: String, #Field("age") age: Int):
Observable<Response<Void>>
}
UPDATE:
The problem has been solved by me.
By adding the url declaration to the app/Http/Middleware/VerifyCsrfToken.php file:
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
'api/add2/*'
];
}

Testing API call in laravel controller/view

I'm testing an API call that I have working in Postman and other interfaces built over the API, but I'm trying to actually get my return values within my laravel site.
Should be simple enough, I made a very bare service file that uses guzzle to get to the API url, and I have a function in there for logging in using a test email, password and client ID (all of which work in the api interface such as Postman)
I'm calling the class and function inside my authController and then returning the function call in the view, then dumping that inside the view.
However, currently I'm getting null on my page dump.
Is there something I'm missing here, possibly in my service file. I don't think there should be anything passed here, but maybe I'm overlooking something more obvious.
Authorize.php
<?php
namespace App\Services\restAPI;
use Illuminate\Support\Facades\Auth;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
use Session;
use Exception;
class AuthService
{
protected $baseurl;
protected $guzzleClient;
public function __construct() {
$this->baseurl = config('http://ip.address');
$this->baseurl = rtrim($this->baseurl, '/') . '/'; // ensure trailing slash
$this->guzzleClient = new \GuzzleHttp\Client(
['verify' => config('app.ca_pem_file'),
'headers' => [
'Event-ID' => ACCESS_EVENT_ID
],
'base_uri' => $this->baseurl
]
);
}
public function loginGetToken(){
$password = "password";
$email = "test#thisAPI.com";
$client_id = "0";
$payload = (object)[
'password'=>(string)$password,
'email'=>(string)$email
];
$retval = $this->post('login/?client_id='.$client_id,$payload);
return $retval;
}
private function post($endpoint,$payload){
$result = $this->guzzleClient->request('POST', $endpoint, ['json'=>$payload]);
$body = $result->getBody();
return json_decode($body);
}
}
AuthController.php
use Redirect;
use Illuminate\Http\Request;
use App\Services\restAPI\AuthService;
class AuthController extends Controller
{
public function login(Request $request)
{
$authService = new AuthService();
$login = $authService->loginGetToken();
return redirect(route('auth.login'))
->with('login', $login)
}
login.blade.php
<?php
dd($login);
?>
Since you are redirecting, the data is not directly available in the view as a variable. It should be in the session though, so you can try this in your view:
dd(session('login'));
https://laravel.com/docs/5.7/redirects#redirecting-with-flashed-session-data

Laravel5.3 session not working in controllers class

i am using laravel 5.3
Session not storing in controllers class method
I think the problem is with connect to api. after connect to api session not work
`
namespace App\Http\Controllers;
use App\GlosbeTranslate as Translate;
use Illuminate\Http\Request;
class translateLocal extends Controller
{
public $arrayDefine;
public function translate($word){
//connect to glosbe Api to translate from eng to fas
$glosbe = new Translate("eng", "fas");
$glosb=$glosbe->translate($word);
$result=json_decode($glosb);
//store result of glosbe api in array
foreach ($result->tuc as $key=>$value){
if(isset($value->phrase)){
$translate[]=$value->phrase->text;
}else{break;};
}
$sortedArray=$this->sort($translate);
$encodearray=json_encode($sortedArray,JSON_UNESCAPED_UNICODE);
//save in session
session(['name' => $encodearray]);
return $encodearray;
}
public function sort($translate){
usort($translate,function ($a,$b){
return strlen($a)-strlen($b);
});
return $translate;
}
}
// my web.php
Route::get('glosb/{word}', 'translateLocal#translate');
Route::get('/session', function () {
echo session('name');
});
when i load mysite.dev/session it's not show my session.
how can i solve that?
Can you give it a try?
Change
use App\putSession;
to
use Session;
You should update your code like:
use Session;
session(['name' => $encodearray]);
TO
Session::put('name',$encodearray]);
and change your route /session like:
Route::get('/session', function () {
$name = Session::get('name');
echo $name;
OR
echo session('name');
});

Attaching a unique identifier to laravel request

Is there a package for laravel that ads a unique identifier to each request in order to use it also for logs?
For example: I would know that request-id as12121-1212s-121 had an error and I could look into logs for any errors.
That request-id would be seen in the UI and I could debug when getting a printscreen with the error from the client
You can use $request->fingerprint()
This prints a uniqueid from your request and you can track it
public function fingerprint()
{
if (! $route = $this->route()) {
throw new RuntimeException('Unable to generate fingerprint. Route unavailable.');
}
return sha1(implode('|', array_merge(
$route->methods(),
[$route->getDomain(), $route->uri(), $this->ip()]
)));
}
If you need a unique id per request you can assign a uuid to the request via global middleware.
For example:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class RequestUniqueId
{
public function handle(Request $request, Closure $next)
{
$uuid = (string) Str::uuid();
$request->headers->set('X-Request-ID', $uuid);
return $next($request);
}
}
This package might help
Laravel Request Logger

Logging a user in manually on Laravel 5

I'm using facebook JS to log in users to a laravel 5 application.
I'm able to add the information to the database correctly but I'm trying to log the user in manually and can't figure it out.
Here is my controller:
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\lib\TopAdditions;
use App\Http\lib\GeneralFunctions;
use App\User;
class FacebookLoginController extends Controller{
public function FacebookRegistration(){
$facebook = new User();
$isThereAUser = User::where('name', $_GET['name'])->get();
if(!count($isThereAUser) > 0){
$facebook->name = $_GET['name'];
$facebook->email = $_GET['email'];
$facebook->password = sha1($_GET['password']);
$facebook->remember_token = $_GET['token'];
$facebook->save();
$id = User::where('name', $_GET['name'])->get();
$this->LoginUser($id);
}
}
public function LoginUser($id){
\Auth::login($id[0]['id'],true);
}
}
When I run that and there is no such user in the database, the user is created and I get this message when the manual login is attempted:
ErrorException in Guard.php line 425:
Argument 1 passed to Illuminate\Auth\Guard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, integer given
I've been searching the web for similar situations but couldn't find anything that will help...
Please help me!
You should pass the user object, not the id, to Auth::login. So just change your function to be like this:
public function LoginUser($user){
\Auth::login($user, true);
}
I had the same problem, this is the solution that worked for me in Laravel 5.4:
public function LoginUser($id){
$user = User::find($id);
auth()->login($user);
}

Categories