I get this error on Digital Ocean Ubuntu server after deployment. It works perfectly on Heroku which is our staging server. It is a Laravel project where we use Laravel Passport. How do we solve this?
<?php
namespace App\Http\Traits;
use Illuminate\Support\Facades\Http;
use Laravel\Passport\Client as AuthClient;
use Exception;
trait AuthTrait
{
public function getTokenAndRefreshToken($email, $password)
{
try {
$auth_client = AuthClient::where('password_client', 1)->first();
$url = env('APP_URL') . "/oauth/token";
$response = Http::asForm()->post($url, [
'grant_type' => 'password',
'client_id' => $auth_client->id,
'client_secret' => $auth_client->secret,
'username' => $email,
'password' => $password,
'scope' => '*'
]);
$result = json_decode((string) $response->getBody(), true);
return $result;
} catch (Exception $e) {
throw $e;
}
}
}
Related
I'm using an apache virtualhost: 'gradez.loc', each time I try to access the /oauth/token route with cURL or Postman it returns a 404.
When I use php artisan serve and try to access to route via http://localhost:8000 there is no problem and I get back the access and refesh token.
What I have done already:
ran php artisan route:list I can see it returns all the passport routes correctly,
ran php artisan route:cache and php artisan route:clear
ran php artisan optimize
None of these seem to fix the problem unfortunately. I see a lot of people struggling with the same problem, but there's no good answer to this.
public function boot()
{
$this->registerPolicies();
if (! $this->app->routesAreCached()) {
Passport::routes();
}
Passport::tokensExpireIn(Carbon::now()->addDays(1));
Passport::refreshTokensExpireIn(Carbon::now()->addDays(10));
Gate::before(function ($user) {
if ($user->isSuperUser()) return true;
});
}
requestAccessToken method:
public function getTokenAndRefreshToken(string $email, string $password)
{
$Oclient = $this->getOClient();
$formParams = ['grant_type' => 'password',
'client_id' => $Oclient->id,
'client_secret' => $Oclient->secret,
'username' => $email,
'password' => $password,
'scope' => '*'];
return $this->sendRequest("/oauth/token", $formParams);
}
public function sendRequest(string $route, array $formParams)
{
try {
$url = self::BASE_URL . $route;
$response = $this->http->request('POST', $url, ['form_params' => $formParams]);
$statusCode = 200;
$data = json_decode((string)$response->getBody(), true);
} catch (ClientException $e) {
echo $e->getMessage();
$statusCode = $e->getCode();
$data = ['error' => 'OAuth client error'];
}
return ["data" => $data, "statusCode" => $statusCode];
}
public function getOClient()
{
return OClient::where('password_client', 1)->first();
}
and my reponse is :
Client error: `POST http://localhost/oauth/token` resulted in a `404 Not Found` response:
Not Found (truncated...)
array:2 [
"data" => array:1 [
"error" => "OAuth client error"
]
"statusCode" => 404
]
Hey I am having an issue on my prod website trying to log in with Laravel passport. It says my Lcobucci JWT Parser is not instantiable. It works for me locally but not on my remote.
How can I resolve this?
Error:
exception: "Illuminate\Contracts\Container\BindingResolutionException"
file: "/var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php"
line: 1038
message: "Target [Lcobucci\JWT\Parser] is not instantiable while building [Laravel\Passport\PersonalAccessTokenFactory]."
trace: [,…]
Login Controller Method:
public function login(Request $request) {
$login = $request->validate([
'email' => 'required:string',
'password' => 'required:string'
]);
if(filter_var($request->email, FILTER_VALIDATE_EMAIL)) {
//user sent their email
Auth::attempt(['email' => $request->email, 'password' => $request->password]);
} else {
//they sent their username instead
Auth::attempt(['username' => $request->email, 'password' => $request->password]);
}
if(!Auth::check()) {
return response([
'status' => 'fail',
'message' => 'Invalid credentials'
]);
}
$accessToken = Auth::user()
->createToken('authToken')
->accessToken;
return response([
'status' => 'success',
'user' => new User_Resource(Auth::user()),
'access_token' => $accessToken
]);
}
I encountered the same issue as well, in your project composer.json add "lcobucci/jwt": "3.3.3" and execute composer update.
I found this solution on: https://github.com/laravel/passport/issues/1381.
Laravel : "8" and Lcobucci\JWT : "^3.4"
Solution:
use Lcobucci\JWT\Encoding\JoseEncoder;
use Lcobucci\JWT\Token\Parser;
.
.
...
public function GetTokenId(Request $request)
{
// Get the Access_Token from the request
$Token = $request->bearerToken();
// Parse the Access_Token to get the claims from them the jti(Json Token Id)
$TokenId = (new Parser(new JoseEncoder()))->parse($token)->claims()
->all()['jti'];
return $tokenId;
}
if anyone still getting this error that's because $verifiedIdToken->getClaim('sub') has been deprecated in 3.4 and removed in 4.0.
use $verifiedIdToken->claims()->get('sub') this insted.
I cannot get the user data and bearer token at the same time. Using vue 2.5 and laravel 7.2.2
I am using GuzzleHttp to make a request to the server in order to get the token.
In order to the request to go through I run a second php artisan serve --port 8006 command.
User exists in the database - have verified.
My AuthController:
use App\User;
use App\Shop;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use \GuzzleHttp\Client;
use DB;
public function login(Request $request)
{
$user = User::where('email', $request->email)->get();
$client = new Client([
'base_uri' => 'http://127.0.0.1:8006',
'timeout' => 5
]);
try {
$response = $client->request('POST', 'oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 2,
'client_secret' => DB::table('oauth_clients')->where('id', 2)->first()->secret,
'username' => $request->email,
'password' => $request->password,
]
]);
$user->token = $response->getBody();
return $user;
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
if ($e->getCode() === 400 || $e->getCode() == 401) {
return response()->json(['message' => 'Грешно потребителко име или парола'], $e->getCode());
}
return response()->json('Something went wrong on the server.', $e->getCode());
}
}
The response is:
[
{
"id": 1,
"name": "Nelly",
"email": "n#n.com",
"email_verified_at": null,
"created_at": "2020-04-05T11:18:30.000000Z",
"updated_at": "2020-04-05T11:18:30.000000Z"
}
]
If I make the method to return $response->getBody() I get the bearer token only.
If I make the method to return $user I get the user only
Tried using GuzzleHttp\Promise\Promise as follows:
public function login(Request $request)
{
$user = User::where('email', $request->email)->get();
$client = new Client([
'base_uri' => 'http://127.0.0.1:8006',
'timeout' => 5
]);
try {
$promise = $client->requestAsync('POST', 'oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 2,
'client_secret' => DB::table('oauth_clients')->where('id', 2)->first()->secret,
'username' => $request->email,
'password' => $request->password,
]
]);
$promise->then(
// $onFulfilled
function ($value) {
dd('The promise was fulfilled.');
},
// $onRejected
function ($reason) {
dd('The promise was rejected.');
}
);
dd('outside of the then');
}
}
Every attempt returns "outside of the then"
So basically you are sending an http request to yourself to get logged in. why don't you just do a normal check and create access token manually
I know this is not guzzle but I thought it might be helpful
Source
if (! Auth::attempt($request->only(['email', 'password']))) {
throw new \Exception('User not found');
}
/** #var User $user */
$user = Auth::user();
$token = $user->createToken('Token Name')->accessToken;;
dd($token);
I am developing an API using Laravel Passport for authentication and my problem is that I cannot change the default message when the login fail due to invalid credentials.
LoginController.php
public function login(Request $request) {
$this->validate($request, [
'username' => 'required',
'password' => 'required'
]);
return $this->issueToken($request, 'password');
}
IssueTokenTrait.php
public function issueToken(Request $request, $grantType, $scope = "") {
$params = [
'grant_type' => $grantType,
'client_id' => $this->client->id,
'client_secret' => $this->client->secret,
'scope' => $scope
];
if($grantType !== 'social'){
$params['username'] = $request->username ?: $request->email;
}
$request->request->add($params);
$proxy = Request::create('oauth/token', 'POST');
return Route::dispatch($proxy);
}
When I put invalid credentials, it returns:
{
"error": "invalid_credentials",
"error_description": "The user credentials were incorrect.",
"message": "The user credentials were incorrect."
}
I want to change this message because I want the message to depend on the language.
Not sure but i try my best to answer you.
use League\OAuth2\Server\Exception\OAuthServerException;
public function issueToken(Request $request, $grantType, $scope = "",ServerRequestInterface $service_request) {
$params = [
'grant_type' => $grantType,
'client_id' => $this->client->id,
'client_secret' => $this->client->secret,
'scope' => $scope
];
if($grantType !== 'social'){
$params['username'] = $request->username ?: $request->email;
}
$request->request->add($params);
$proxy = Request::create('oauth/token', 'POST');
throw OAuthServerException::invalidRequest('access_token', object_get($error,
'error.message'));
return Route::dispatch($proxy);
}
Change App\Exceptions\Handler.php under:
public function render($request, Exception $exception)
{
...
$class = get_class($exception);
...
if ($class == 'League\OAuth2\Server\Exception\OAuthServerException' ){
return response()->json([
'code'=>$exception->getHttpStatusCode(),
'error'=>$exception->getMessage(),
'error_type'=>$exception->getErrorType()
],
$exception->getHttpStatusCode());
}
...
return parent::render($request, $exception);
}
I am trying to implement GuzzleHttp Application in my React/Laravel App.
This is my Routes:
This is my Controller Code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function login(Request $request){
$http = new \GuzzleHttp\Client;
try {
$response = $http->post(route('passport.token'), [
'form_params' => [
'grant_type' => 'password',
'client_id' => config('gocv.passport.client_id'),
'client_secret' => config('gocv.passport.client_secret'),
'username' => $request->username,
'password' => $request->password,
],
'headers' => [
// 'User-Agent' => 'testing/1.0',
'Accept' => 'application/json'
]
]);
return $response->getBody();
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
if($e->getCode() == 400)
{
return response()->json('Invalid Request. Please Eneter username and password', $e->getCode());
}
else if($e->getCode() == 401)
{
return response()->json('Invalid Credentials', $e->getCode());
}
return response()->json('Something Went Wrong', $e->getCode());
}
}
}
This is my Postman Request:
When I am trying to do Post Request on this route: (api/login) it does not return any response. server just stops working and I need to restart it.
Enviroment is AWS Cloud9, php version 7.2 and laravel version 5.7 running with only php artisan serve --port=8082 --host=0.0.0.0
Note: when I send get request on other site ex: github.com it returns response. the problem is when I am trying to do request on same IP.
PS. when I try to login on route /oauth/token it works and returns token
Any answer will be apreciated . Thanks.