Authentication in Lumen 5.2 - laravel

In the AuthServiceProvider;
Auth::viaRequest('api', function ($request) {
if ($request->input('api_token')) {
return User::where('api_token', $request->input('api_token'))->first();
}
});
I can't seem to get this to work. GET requests do not have a body so no input is present.
Also I've tried using $request->header('api_token') but still getting unauthorised
If I do an independent search on the DB like below it works;
Auth::viaRequest('api', function ($request) {
return User::where('api_token', 'my_api_key')->first();
});
Can anyone confirm that the $request header can be accessed here?

Before you read my answer, please read this article (just in case you're using Apache Web Server).
Headers containing invalid characters (including underscores) are now silently dropped.
Ok, now to get your api_token value, you need to change your request header-field name to Api-Token (this is standard, you may read this).
Now you can access your Api-Token value via:
$request->header('Api-Token', 'any-default-value');
If you really want to get your non standard header definition, you may use getallheaders function. For more information, you may read Symfony\Component\HttpFoundation\ServerBag#getHeaders method.

Related

Laravel - retrieve data inside controller – POST x PATCH

First important information: I’m new to laravel, so your patience is appreciated.
I’m currently migrating a framework of mine to laravel, so I’m in the early stages.
Currently, I’m trying to set up an API endpoint to make small changes on some records. I’ve already managed to set up a API for inserting records and works perfectly. However, for setting up an API for small changes (patch), I’m having difficulties, probably because I’m not fully familiar with laravel’s Request class.
My successful insert set up looks like this:
\routes\api.php
Route::post('/categories/',[ApiCategoriesInsertController::class, 'insertCategories'], function($insertCategoriesResults) {
return response()->json($insertCategoriesResults);
})->name('api.categories.insert');
\app\Http\Controllers\ApiCategoriesInsertController.php
// some code
public function insertCategories(Request $req): array
{
$this->arrCategoriesInsertParameters['_tblCategoriesIdParent'] = $req->post('id_parent');
// some code
}
With this set up, I’m able to retrieve “id_parent” data set through POST.
So, I tried to do exactly the same architecture for patch, but doesn’t seem to work:
\routes\api.php
Route::patch('/records/',[ApiRecordsPatchController::class, 'patchRecords'], function($patchRecordsResults) {
return response()->json($patchRecordsResults);
})->name('api.records.patch');
\app\Http\Controllers\ApiRecordsPatchController.php
// some code
public function patchRecords(Request $req): array
{
$this->arrRecordsPatchParameters['_strTable'] = $req->post('strTable');
// some code
}
In this case, I´m using postman (PATCH request), testing the data in the "Body tab" with key "strTable" and value "123xxx" and I´m receiving “strTable” as null.
Any idea of why this is happening or if I should use another method in the Request class?
Thanks!
You can access parameters on the Request object using one of the following methods:
$req->strTable;
// or
$req->input('strTable');
The input method also accepts a second parameter which will be used as the default return value if the key is not present in the Request.
If you want to check whether or not the Request contains a value before you attempt to access it, you can use filled:
if ($req->filled('strTable')) {
// The request contains a value
}
Turns out that the way I had set up was in fact working and retrieving data:
$req->post('strTable');
The problem was in how I was testing it. In postman, there are several options to configure:
form-data
x-www-form-urlencoded
raw
binary
I had already switched to x-www-form-urlencoded to test it, but I forgot to fill the “key” and “value” information again. I didn’t realize that the fields blank as we switch between them.
Summing it up: It works when x-www-form-urlencoded selected but doesn’t work with form-data selected. Don’t know what the difference between them yet, but I’ll research it further.
By the way, it worked also with the suggestion from Rube Hart:

Azure Functions proxy to url provided by querystring gives 404

I've set up an Azure Functions proxy (using proxies.json). This should just pick the value given in the original request's url query string parameter and use that as a value for backendUri. So the goal is that the response of the call to the proxy contains the response of calling the URL that's in the url query string parameter directly. I need this because of CORS.
Here's my proxies.json
{
"$schema": "http://json.schemastore.org/proxies",
"proxies": {
"proxy1": {
"debug": true,
"matchCondition": {
"methods": ["GET"],
"route": "/proxy/"
},
"backendUri": "{request.querystring.url}"
}
}
}
When I call the proxy using https://not-an-actual-url.azurewebsites.net/proxy/?url=https://stackoverflow.com I'm getting back a 404. Same if I encode the value of the url parameter. If I set the backendUri in proxies.json to a static URL instead of trying to use the query string, it works, however.
To summarize, I want the value of backendUri to depend on the URL of the original request. As stated in the docs this should be possible. Quote from the docs:
Set the backend URL to another endpoint. This endpoint could be a function in another function app, or it could be any other API. The value does not need to be static, and it can reference application settings and parameters from the original client request.
When I call the proxy using
https://not-an-actual-url.azurewebsites.net/proxy/?url=https://stackoverflow.com
I'm getting back a 404. Same if I encode the value of the url
parameter. If I set the backendUri in proxies.json to a static URL
instead of trying to use the query string, it works, however.
Judging from your problem description, you don't seem to have a real HttpTrigger. You want to use function app as a server to forward requests to an address, right?
I think it is unrealistic that you want to dynamically get the url from the request and apply it to proxies.json. Because this file is already loaded when the function app is started, you cannot let the requested information enter, it will read your value as a normal string, if it is not a direct url, it cannot be read.
For CORS, you can find some free and public servers for forwarding, or build a server for forwarding by yourself. The proxies.json of function app may not realize your idea.

laravel request return message keys translations

I have a Laravel Application and another APP making calls via API to Laravel. These 2 projects are separated.
Laravel and App have their own multilanguage system. They work independently but uses the same key translations.
So my idea was that all Laravel responses must be translations key, like: 'messages.success'.
With this response, the App can translate it.
All of these are working fine.
The problem appeared when I started working with Laravel Requests for validating forms.
In this case, the validation errors are automatically translated so the App receives the response translated with the default language of the Laravel application.
So what can I do?
I thought with 2 ideas but I don't know if they can work.
1: Passing the language into params. Don't know if it can work, how can I set the language before Laravel validates the Request?
2: Override the functionality of Requests to return messages without translate, so instead of "Felicidades" return "messages.success". I really like this approach. But how can I do it for all the rules? Overriding the messages function like this:
public function messages()
{
return [
'unique' => 'validation.unique'
];
}
For every rule works... but I feel bad.
Another approaches?
What is the best way to fix this problem?
I would suggest that you use this hacky solution in 2 lines of code. Go to /resources/lang/{code}/validation.php. You can see that it returns an array of messages by default. Modify it like so:
// Replace return in the first line
$ret = [
/* all the translations go here as normal */
];
// Add this as the last line. This will replace all values with their keys.
return array_combine(array_keys($ret), array_keys($ret));
After that you can use validation as per usual and you'll get validation message keys instead of messages. Cheers and hope this helps.

Laravel $request->all() correctly returns data, but $_POST completely empty

I am making an ajax post request to the server, posting json data. In firebug I can see the network post call going through along with the json data.
In Laravel I was trying to do a simple var dump of the $_POST data and have just wasted a fair bit of time being confused as to why this should be completely empty. However, when I use the Request facade, my data is there.
ie. this just gives me an empty array:
public function test(){
Log::info($_POST);
}
...yet this prints my data, as I expect:
public function test(Request $request){
Log::info($request->all());
}
Why?
Edit
Thanks, #Webdesigner. The http verb is definitely post, as my method is called in my routes file via
Route::post('/image-upload', 'EntryController#test'); // Note "post" verb
I don't think $request->post() is valid in Laravel 5.4 as this throws an BadMethodCallException: Method post does not exist. error. However, I can confirm that
Log::info($request->method()); // POST
also tells me the method is post.
Very strange. I guess you're right that some part of the app is overwriting the $_POST global, though I have no idea why/where/how. Probably not relevant, but this call is being made from Angular 4.
Thanks for your help anyway!
This is not the normal behavior of Laravel. I tested this on a fresh Laravel 5.5 site and just did a Form submit and an Ajax POST request to the same Route.
Both give me the same result. A POST Request should have at least the CSRF Token as _token with a value.
One other point is $request->all() is not only the the content of $_POST so to have a fair compression you should try $request->post().
BTW only because you did a POST request do not mean that the data is send by the POST Method, it could be that the data you see in $request->all() is from $_GET and $_COOKIE, etc and only the Method was a POST.
Last but not least there it the option that some part of your APP is deleting the content of the Superglobal Variables. $_POST and the others are not like constants, so they can be changed during runtime e.g. $_POST = [];
I don't thing that there is a difference in Laravel 5.4.27.

Send object with axios get request [duplicate]

This question already has answers here:
Axios get in url works but with second parameter as object it doesn't
(4 answers)
Closed 5 years ago.
I want to send a get request with an object. The object data will be used on the server to update session data. But the object doesn't seem to be sent correctly, because if I try to send it back to print it out, I just get:
" N; "
I can do it with jQuery like this and it works:
$.get('/mysite/public/api/updatecart', { 'product': this.product }, data => {
console.log(data);
});
The object is sent back from server with laravel like this:
public function updateCart(Request $request){
return serialize($request->product);
The same thing doesn't work with axios:
axios.get('/api/updatecart', { 'product': this.product })
.then(response => {
console.log(response.data);
});
I set a default baseURL with axios so the url is different. It reaches the api endpoint correctly and the function returns what was sent in, which was apparently not the object. I only get "N; " as result.
Axios API is a bit different from the jQuery AJAX one. If you have to pass some params along with GET request, you need to use params property of config object (the second param of .get() method):
axios.get('/api/updatecart', {
params: {
product: this.product
}
}).then(...)
You can pass either a plain object or a URLSearchParams object as params value.
Note that here we're talking about params appended to URL (query params), which is explicitly mentioned in the documentation.
If you want to send something within request body with GET requests, params won't work - and neither will data, as it's only taken into account for PUT, POST, DELETE, and PATCH requests. There're several lengthy discussions about this feature, and here's the telling quote:
Unfortunately, this doesn't seem to be an axios problem. The problem
seems to lie on the http client implementation in the browser
javascript engine.
According to the documentation and the spec XMLHttpRequest ignores the
body of the request in case the method is GET. If you perform a
request in Chrome/Electron with XMLHttpRequest and you try to put a
json body in the send method this just gets ignored.
Using fetch which is the modern replacement for XMLHtppRequest also
seems to fail in Chrome/Electron.
Until it's fixed, the only option one has within a browser is to use POST/PUT requests when data just doesn't fit into that query string. Apparently, that option is only available if corresponding API can be modified.
However, the most prominent case of GET-with-body - ElasticSearch _search API - actually does support both GET and POST; the latter seems to be far less known fact than it should be. Here's the related SO discussion.

Resources