Laravel JWT Auth Token invalid / Signature could not be verified - laravel

I'm getting pretty tired of this error.. Stuck for 2 days now.
I do receive a token on valid credentials, but my token stays invalid, no matter if I pass it through url parameter (?token=[token]) or as Auth header (Bearer: [token]).
Anyone still experiencing this? I followed everything in the tutorial. Also configured both .htaccess in my public folder, and in my apache configuration.
Route::get('/test', function () {
return JWTAuth::parseToken()->authenticate();
});
Going to this route returns
TokenInvalidException in NamshiAdapter.php line 71:
Token Signature could not be verified.
For lookups, here is my authentication method from my AuthController.php
public function authenticate(Request $request) {
$credentials = $request->only('email', 'password');
$user = User::where('email', Input::get('email'))->first();
try {
if (!$token = JWTAuth::attempt($credentials)) {
return $this->respondUnauthorized();
}
} catch (JWTException $e) {
return $this->respondInternalError('Could not create token!');
}
// dd()
return $this->respond([
'token' => compact('token'),
'user' => $user]);
}
My routes middleware group:
Route::group(['middleware' => ['jwt.auth', 'jwt.refresh']], function() {
When I check line 71 in my NamshiAdapter and I dd() my token it says my secret is empty...
There must be something wrong? Is this just a minor bug or am I missing something?

in Laravel 5.5 (in my case):
1- Run the command:
php artisan jwt:secret
you should see this result:
jwt-auth secret [mygeneratedsecret] set successfully.
2- copy the secret, which is between the bracket (mygeneratedsecret) and add it to the .env file as following:
JWT_SECRET=mygeneratedsecret
3- Make sure your configuration file jwt.php has the secret set as following:
'secret' => env('JWT_SECRET'),
Important Note:
Don't forget to Re-generate the Token (using your login script or whatever you use), because the old token (before the secret configuration)
will still be invalid against the new secret
Happy Coding :)

I had the same issue
the solution is what jycr753 have said... "setting the api secret in jwt.php"
in fact on config/jwt.php, there is the line'secret' => env('JWT_SECRET'),,
Generate the key with this helper php artisan jwt:generate (for some reason I dont know why it doesnt set in the .env file itself like php artisan key:generate).
Copy the key (jwt-auth secret [DSvO98YtJ0204mBu9zqWN9QOMX7Tmvr9] set successfully.) without the bracket and add it in .env file like JWT_SECRET=DSvO98YtJ0204mBu9zqWN9QOMX7Tmvr9 or you can change it straigth in jwt.php secret' => env('DSvO98YtJ0204mBu9zqWN9QOMX7Tmvr9')

Related

Laravel Route URL in Notification Email Defaults to HTTP

I am creating email notifications in Laravel 9 that contain a button with a URL. I am using the name attribute from the route to pass along the proper route from the web.php file.
When the user gets the email notification, the URL defaults to "http://" rather than "https://".
I have the proper HTTPS redirect on the server, but I'd like the original URL to default to HTTPS. Any idea how to do this?
Example route from web.php:
Route::get('/home', [HomeController::class, 'home'])->name('home');
Example notification button line in the HomeController:
$notify_data = [
... content stuff here ...
'url' => route('home' ),
];
$user->notify( new Step3($notify_data) );
And finally the button in the Step3 Notification:
public function toMail($notifiable)
{
return (new MailMessage)
... content stuff here ...
->action('View Dashboard', $this->notify_data['url']);
}
Expectation:
URL in email: https://www.example-domain.com/home
Current result:
URL in email: http://www.example-domain.com/home
Use secure_url method
'url' => secure_url(route( 'home', [], false)),
The secure_url function generates a fully qualified HTTPS URL to the given path. Additional URL segments may be passed in the function's second argument:

Laravel Vue SPA using Sanctum response Unauthorized

The Sanctum Auth system on my local machine works well and I have no errors. But my deployed app is having trouble with authorizing a user. When I login it sends a request to get the user data then redirects. After auth completes you are redirected and the app make a GET request for more data. This GET route is guarded using laravel sanctum. But the backend is not registering that the user has made a successful login attempt so it sends a 401 Unauthorized error. Here is some code...
loadUser action from store.js
actions: {
async loadUser({ commit, dispatch }) {
if (isLoggedIn()) {
try {
const user = (await Axios.get('/user')).data;
commit('setUser', user);
commit('setLoggedIn', true);
} catch (error) {
dispatch('logout');
}
}
},
}
Route Guard on the routs.js checking to see isLoggedIn (which is just a boolean store locally)
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// if (to.meta.requiresAuth) {
if (isLoggedIn()) {
next();
} else {
next({
name: 'home'
});
}
} else {
next();
}
})
It was pointed out that I had forgotten the withCredetials setting for axios in bootstrap.js. I made this addition but my issue still remains.
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.withCredentials = true;
Route middleware guard on the server side (this is where the request is getting turned away)
Route::middleware('auth:sanctum')->group(function () {
Route::apiResource('trucks', 'Api\TruckController');
});
In the laravel cors.php config file I changed the "supports_credentials" from false to true
'supports_credentials' => true,
It seems to me that the cookie information is not being over the api call (but I'm really not sure). This setup is working on my local machine but not on the server that I have deployed to.
Needed to add an environment variable to the .env file for SANCTUM_STATEFUL_DOMAINS and made that equal the domain name.
In the laravel sanctum.php config file...
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost,127.0.0.1')),

laravel_token is valid for first request but not subsequent requests

I have installed Laravel Passport and configured it according to the documentation. When calling axios.get from my VueJS file, the first call works as expected. the laravel_session Request Cookie is injected into the request, and the authentication passes, returning the resource.
My problem arises when I try to call the axios.get method again. My use case here is a search function. I'm making a call to /api/banking/accounts/search/{search-term} whenever the user types into a text field, using the code below:
remoteMethod(query) {
if (query !== '') {
this.loading = true;
axios.get(
`/api/banking/accounts/search/${escape(query)}`
).then(res => {
this.destinationAccountDirectory = res.data;
this.loading = false;
});
} else {
this.destinationAccountDirectory = [];
}
},
This code works fine without any auth:api middleware on the route, and for the first time with auth:api middleware. As can be seen from the screenshots below, the laravel_token value changes and is rejected on subsequent calls to the API.
**I've tried to removed the \Laravel\Passport\Http\Middleware\CreateFreshApiToken that was added to the web middleware group during passport installation, which seemed to have temporarily solved the issue, until I receive a 419 on a request shortly after. What could be causing the new laravel_tokens to be rejected? **
I solved this by removing the web middleware from my API route. Why it was there in the first place, I have no idea.
I changed my api.php from
Route::group([
'middleware' => [
'web',
'auth:api']], function() {
Route::post('/banking/transactions', 'TransactionController#store');
Route::get('/banking/accounts', 'BankAccountDirectoryController#index');
Route::get('/accounts/{account}', 'BankAccountDirectoryController#show');
Route::get('/banking/accounts/search/{term?}', 'BankAccountDirectoryController#search');
});
to
Route::group([
'middleware' => [
'auth:api']], function() {
Route::post('/banking/transactions', 'TransactionController#store');
Route::get('/banking/accounts', 'BankAccountDirectoryController#index');
Route::get('/accounts/{account}', 'BankAccountDirectoryController#show');
Route::get('/banking/accounts/search/{term?}', 'BankAccountDirectoryController#search');
});
Should the API routes be under the web group to benefit from the middleware, or is it purely for UI? Am I safe to do this?

Laravel Queue mail doesn't work, but send mail works

i have a very strange problem.
If i use laravel send mail everything works perfect.
but when i queue a mail it give a this error.
but the very strange part is, that yesterday my code did work!! without changing anything now
this works:
Mail::send('emails.empty',
$invoice, function ($m) use ($invoice) {
$m->from('hello#app.com', 'Your Application');
$m->to($invoice['customer_email'], $invoice['customer_name'])
->subject($invoice['email_subject']);
});
But this doesn't work
Mail::later(1, 'emails.empty',
$invoice, function ($m) use ($invoice) {
$m->from('hello#app.com', 'Your Application');
$m->to($invoice['customer_email'], $invoice['customer_name'])
->subject($invoice['email_subject']);
});
Also with the new 5.3 way it doesn't work
$user = new App\User();
$user = $user->find(1);
Mail::to($user)->queue(new EmailTest($user));
This is the faild job error:
Swift_TransportException: Expected response code 250 but got code "", with message "" in /private_html/dev1/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php:383
Stack trace:
#0 .......................
I use mailtrap to send/catch my emails. with the same settings de SEND function works! so its not the settings

Google api php redirect_uri_mismatch

When using the following composer package bitgandtter/google-api for google php api client since I'm using it in combination with laravel 4 I get the following error redirect_uri_mismatch. My code looks like this(which is located under app/lib using the PSR-0 spec):
class Google {
private $client;
private $token;
public function __construct($code)
{
$this->client = new Google_Client();
$this->client->setApplicationName("camelCaseD");
$this->client->setClientId('SOMENUMBERS.apps.googleusercontent.com');
$this->client->setClientSecret('PRECIOUS');
$this->client->setRedirectUri('http://localhost:9000/auth/google');
$this->client->authenticate($code);
}
}
My routes are:
Route::group(['prefix' => 'auth'], function()
{
Route::post('google', function()
{
$postInput = file_get_contents('php://input');
try
{
$google = new Google($postInput);
} catch (Exception $e)
{
return Redirect::to('signin')->with('error', $e->getMessage());
}
});
});
I'm using the official google plus sign in button to log the user in then passing the authorization code to my server via $.ajax().
Here's what my api console settings look like:
I got that similar error. To resolve mine, I went to google console and reset the secret. I also made sure the Authorized JavaScript origins was set to the correct address.
http:// localhost :900/auth/google
is a directory or a page?
Maybe if it is a directory, the final url is different (like http:// localhost :900/auth/google/index.php) and Google does a control between 2 string, but they are different.

Resources