How to login into a Laravel app using cURL - laravel

I want to setup a small file of cURL requests so I can quickly test my Laravel app's API quickly.
Unfortunately, I'm stuck at logging in :D.
This is what I have so far:
curl -H "Accept: application/json" -d #./curl/user.json http://localhost:8000/login -o ./curl/response.json -v
I have a user.json file that has my login info:
{
"email": "boss#example.com",
"password": "password",
}
And I would like to output the data into my response.json file.
Nothing is working though. I have a poor understanding of a couple of these technologies. Anyone able to hold my hand through this?
With the -v tag, I'm getting:
connect to ::1 port 8000 failed: Connection refused
* Trying 127.0.0.1:8000...
* Connected to localhost (127.0.0.1) port 8000 (#0)
> POST /login HTTP/1.1
> Host: localhost:8000
> User-Agent: curl/7.77.0
> Accept: application/json
> Content-Length: 81
> Content-Type: application/x-www-form-urlencoded
>
} [81 bytes data]
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Host: localhost:8000
< Date: Mon, 17 Jan 2022 01:47:53 GMT
< Connection: close
< X-Powered-By: PHP/7.4.27
< Cache-Control: no-cache, private
< Date: Mon, 17 Jan 2022 01:47:53 GMT
< Content-Type: application/json
< Set-Cookie: laravel_session=eyJpdiI6IkpoUkhoQnNWdEVhYUdGU2wzckg5c3c9PSIsInZhbHVlIjoidGwrUHpBcDV4Z2lXNWdObmQrdER2OUp0aEIveXhpdFNREmovedSomeSTufffForSecurityPurposesmNyb3oiLCJtYWMiOiIyZTY2Yzk1MWY3MDA3M2I3NDkzMmQzMTUwMjcyNDFmMTU3MTU
0MzRmZjAzNDBjZmZmZTgwMjg1MjMzOThkZmU5IiwidGFnIjoiIn0%3D; expires=Mon, 17-Jan-2022 03:47:53 GMT; Max-Age=7200; path=/; httponly; samesite=lax
<
Any idea how I can login to a Larvel app using cURL? The goal is to make it work like Postman, but in the terminal!

I want to setup a small file of cURL requests so I can quickly test my Laravel app's API quickly.
Any idea how I can login to a Larvel app using cURL? The goal is to make it work like Postman, but in the terminal!
Login using Laravel's default authentication page and API authentication are two different things. I can't explain to you about API authentication in depth, as it would be quite lengthy.
Laravel has two packages that you can use for this case, Passport and Sanctum.
Sanctum is automatically installed when you install Laravel.
Since middleware on web is different from API, you should focus on route routes/api.php. You can create a token generation route (same as login). For example :
Route::post('/token', function (Request $request) {
// You can replace it with your login logic
$user = User::first();
$token = $user->createToken('Your Awesome Token Name');
return ['token' => $token->plainTextToken];
});
Return :
{
"token": "1|jLw1HhWJhSVQq81VFZwhxYB93GKMl5JRCrtuYQ36"
}
Then, the generated token you can use to access other API routes.
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Calling via cURL :
curl -i http://your-awesome-app.test/api/user -H "Authorization: Bearer <TOKEN>"
Change <TOKEN> :
curl -i http://your-awesome-app.test/api/user -H "Authorization: Bearer 1|jLw1HhWJhSVQq81VFZwhxYB93GKMl5JRCrtuYQ36"
Viola!!!
{
"id":1,
"name":"Your Awesome User",
"email":"your.awesome#user.test",
"email_verified_at":"2022-01-17T03:03:58.000000Z",
"created_at":"2022-01-17T03:03:58.000000Z",
"updated_at":"2022-01-17T03:03:58.000000Z"
}

Related

Curl lets me GET but does not let me POST ... Spring JPA

When I run the Spring Application and then try to comunicate with
the REST API it allows me to GET but not to POST.
So this works:
curl -u user:a75fd7ea-9a6e-4943-bc0c-3b0a96bda51b http://localhost:5000/activity/getall
This does not work:
curl -u user:a75fd7ea-9a6e-4943-bc0c-3b0a96bda51b
-H "Accept: application/json"
-X POST
-d '{
"name":"Sleep",
"criteria":"Sleep at least 8 hrs",
"ini":"2022-08-30",
"periodicity":"DAY",
"periodicityCount":"1"
}'
http://localhost:5000/activity/post
If you notice is the same Username and Password.
This is the response I get:
HTTP/1.1 403
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Transfer-Encoding: chunked
Date: Mon, 29 Aug 2022 19:25:27 GMT
Connection: close
{
"timestamp": "2022-08-29T19:25:27.510+00:00",
"status": 403,
"error": "Forbidden",
"path": "/activity/post"
}
The reason why your API calls fail is due to the CSRF protection you enabled in your Spring Security configuration.
The way this works is that for each non-GET request (= POST, PUT, PATCH or DELETE), you need to include a CSRF token.
To obtain a CSRF token, you first need to fire a GET request (eg. http://localhost:5000/activity/getall). In the response headers, you should see a Set-Cookie header containing an XSRF-TOKEN cookie. For example:
Set-Cookie: XSRF-TOKEN=098b732a-282a-11ed-a261-0242ac120002
Now you need to copy the value of the XSRF-TOKEN cookie (should contain a UUID), and set it as the value of the X-XSRF-TOKEN header:
curl \
-u user:a75fd7ea-9a6e-4943-bc0c-3b0a96bda51b
-H "Accept: application/json"
-H "X-XSRF-TOKEN: 098b732a-282a-11ed-a261-0242ac120002"
-X POST \
-d '{
"name":"Sleep",
"criteria":"Sleep at least 8 hrs",
"ini":"2022-08-30",
"periodicity":"DAY",
"periodicityCount":"1"
}'
http://localhost:5000/activity/post
After that, your request should succeed. Be aware, the response of this POST-request will contain a new CSRF token that you will have to copy to your next request.
Alternatively, you can disable CSRF protection by setting .csrf().disable() in your Spring Security configuration.

Laravel Passport - consuming your own api with javascript 401 Unauthenticated

I hope you're doing well. I'm struggling since several days with Laravel Passport, trying to consume my own api with javascript / vuejs. The last evenings were spend reading nearly every existing post about my problem, but I could not find any solution. I hope you can help me, thank you at this point.
I've set up a fresh laravel application and installed Laravel Passport like it its described in this offical doc for Laravel 5.8 (https://laravel.com/docs/5.8/passport#introduction). I've done every single point from the tutorial multiple times in different applications, without any success. To test my setup, I'm using this small axios request.
axios.get('/oauth/clients')
.then(response => {
console.log(response);
}).catch(error => {
console.log(response);
})
When I'm logged in, its works fine, when I use a bearer token and use postman to test '/oauth/clients' it works also fine, but when I'm not logged in it always returns 401 Unauthenticated. My goal is to create an api, that I can consume from my own application as an unauthenticated user without a bearer token, but not from the outside. I thought Laravel Passport is the correct way to do this.
My request headers:
:authority: laravel.dev
:method: GET
:path: /oauth/clients
:scheme: https
accept: application/json, text/plain, */*
accept-encoding: gzip, deflate, br
accept-language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7
cache-control: no-cache
cookie: XSRF-TOKEN=eyJpdiI6IkxTTGs2cEtvbXc5cmhIZDhEV1lBXC9nPT0iLCJ2YWx1ZSI6IlpPcjdCbmlDcURraG03MndjUTVYeTV1WXl1YWx3MVdNWjFrZ1QrRENJcnlhZVVCNWtZdzl5VDN6ZjdkclBGK0siLCJtYWMiOiI3ZmQ4YjlkZmU3OWMyNjNiYWVhNzJhMWVkOGRhOGJhMzJkNWQwZmZjMDhmZDM2Y2IxYWRkODJiNzFhNmQ5NDA1In0%3D; laravel_session=eyJpdiI6IlpKc3EyS2R4NjAyM0t5XC8xaTR6SjJBPT0iLCJ2YWx1ZSI6Im1JRlRReVFHQ01jTlNQT3BkYlI1V0dNeE1BMkVvODhnWXNjM1VPRUFBRWRBRnl1N1diUmpOSkVJUmc0NTdsVFgiLCJtYWMiOiI0ZTZkNzE2OGQ5MzJkY2FmYzEzOWZiYjA3YTRiM2MxOGQ3OGJmNWIzMTI4ODA5MDMxYWVlMjJmOTk1M2FjZDdlIn0%3D
pragma: no-cache
referer: https://laravel.dev/
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36
x-csrf-token: 4Opsva9oDk6LkAapLGqqh9AuPzWKfVH4PYoxcMB1
x-requested-with: XMLHttpRequest
x-xsrf-token: eyJpdiI6IkxTTGs2cEtvbXc5cmhIZDhEV1lBXC9nPT0iLCJ2YWx1ZSI6IlpPcjdCbmlDcURraG03MndjUTVYeTV1WXl1YWx3MVdNWjFrZ1QrRENJcnlhZVVCNWtZdzl5VDN6ZjdkclBGK0siLCJtYWMiOiI3ZmQ4YjlkZmU3OWMyNjNiYWVhNzJhMWVkOGRhOGJhMzJkNWQwZmZjMDhmZDM2Y2IxYWRkODJiNzFhNmQ5NDA1In0=
Response headers:
cache-control: no-cache, private
content-type: application/json
date: Sun, 07 Jul 2019 19:05:25 GMT
server: nginx/1.15.5
set-cookie: XSRF-TOKEN=eyJpdiI6IklTWEkrRTJxYXpiRFNQUm0zM3RLYWc9PSIsInZhbHVlIjoiMDEzSmVlMldQOXBrVUQxQjlCUGVVN2dpUk9VWmwrUlRjend3XC9CaUk1S2V6dUFlTDZtVWttREV5cVBPOFwveVQ0IiwibWFjIjoiZWZhMzA3OGVhYmY2NWNjNjgyMTg4NzAxZjQzNWYxZGQyMjVmMWY3MjAwNjllZTM5ODFiNjFiNWY1NGFjOGM0NiJ9; expires=Sun, 07-Jul-2019 21:05:25 GMT; Max-Age=7200; path=/
set-cookie: laravel_session=eyJpdiI6IlFLUDN0bGhBNW1UTytlbGgrcEZ0ekE9PSIsInZhbHVlIjoibHFvM09CSTFyZ05Kd0E0REVCekNOYmRocm01cnBVY3h1YjFOaXpyTXVcL05QSTNYdFFBdVpXZHd4NDVURGwralwvIiwibWFjIjoiYzM0ZWNhNzQ5MTJhY2VmNTZjZmM1YjFiNTgzYjU0NmZhZGIzZjVjYTFkOGNjYWEwNDEwODUyMzc5OWI2Njc3YiJ9; expires=Sun, 07-Jul-2019 21:05:25 GMT; Max-Age=7200; path=/; httponly
status: 401
Important note: I've shared the project with a friend of mine, he works on MacOs with Laravel in a docker container and the authorization works on his device without any changes. I'm running on a windows machine with Laravel Homestead. Could this problem be caused by Laravel Homestead or nginx?
The route 'oauth/clients' is defined under the 'oauth' prefix (e.g., /oauth/any-route) using both the 'web' and 'auth' middlewares. This explains why you are receiving a 401 error when you are not logged in, as the 'auth' middleware is failing.
/vendor/laravel/passport/src/RouteRegistrar.php
/**
* Register the routes needed for managing clients.
*
* #return void
*/
public function forClients()
{
$this->router->group(['middleware' => ['web', 'auth']], function ($router) {
$router->get('/clients', [
'uses' => 'ClientController#forUser',
'as' => 'passport.clients.index',
]);
...
});
}
Also, you should not be using 'web' middleware for your API routes. The API is stateless and should not receive or respond with any session data. This means no need for CSRF/XSRF tokens, which I can see are being transmitted in your example.
You need to place your API routes within the specified API routes file. You'll notice that the authorization middleware 'auth:api' is also slightly different for API routes.
/routes/api.php
Route::middleware(['auth:api'])->group(function () {
Route::get('/your/path', 'Api\YourController#index');
});
Then in Postman, simply pass your bearer token and expected response type. And don't forget to add the 'api' prefix to your route, as you will do for all routes within the api.php routes file.
/api/your/path
Authorization Bearer {your_token}
Accept application/json
Hope this helps and good luck!
Thank you for your answer #matticustard. I've written a small controller to test the authorization and put the route in the following groupe with auth:api middleware:
Route::group(['prefix' => 'v1', 'middleware' => 'auth:api', 'namespace' => 'Api\v1', 'as' => 'api.'], function () {});
When I use a bearer token and postman it works fine, but I want to use this route also from my application as an user who is not logged in. But only from my application not from the outside, how can I achieve this?
axios.get('/api/v1/test')
.then(response => {
console.log(response);
}).catch(error => {
console.log(response);
})
Thank you for your time :)

Ambari api POST complaining CSRF protection

I am trying to set hbase property through Ambari API using following command
curl -u "admin:admin" -i -X POST -d '{"type": "hbase-site", "tag": "version3", "properties" : {"hbase.regionserver.global.memstore.size" : "0.6"}}' https://abct.net/api/v1/clusters/xyz/configurations
But keep getting following error
HTTP/1.1 400 Bad Request
Content-Length: 107
Content-Type: text/plain
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Server: Microsoft-IIS/8.5
x-ms-hdi-active: 10.8.18.29
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
User: admin
X-Powered-By: ARR/3.0
Set-Cookie: AMBARISESSIONID=2e8ortl32j1p7zdjatigdgvg;Path=/;HttpOnly; path=/; secure
X-Powered-By: ASP.NET
Date: Mon, 12 Sep 2016 18:19:38 GMT
{
"status" : 400,
"message" : "CSRF protection is turned on. X-Requested-By HTTP header is required."
}
What am missing here ?
Turns out you have to add the request header to the request for anything other than a GET request.
You can add the header with
curl --header "X-Requested-By: my_computer_name"
Or
You can disable this feature.
I had same problem in c# Rest client. Using Brig's answer fixed it:
HttpClientHandler handler = new HttpClientHandler
{
Credentials = new System.Net.NetworkCredential("xxxx", "yyyyy"),
};
using (var httpClient = new HttpClient(handler))
{
//"X-Requested-By: my_computer_name"
httpClient.DefaultRequestHeaders.Add("X-Requested-By","my_computer_name");

Getting 400 Bad Request with Grails Spring Security Rest Plugin

I'm trying grails restful spring security rest plugin.
I'm using Grails 2.5.2 with spring-security-rest:1.5.2.
I'm unable to make login work with the following ajax call. I get 400 bad request. But if I try to use CURL command it works! I don't understand what's wrong.
That's the ajax post call:
var config = {
type : 'POST'
,url : '/api/login'
,data : {username:"xxxx",password:"xxxx"}
,async : false
,dataType : 'JSON'
,contentType: "application/json;charset=utf-8"
,success: function(response) {
console.dir(response);
}
,error : function (response) {
console.dir(response);
}
}
$.ajax(config);
Spring rest plugin configuration inside Config.groovy is:
grails.plugin.springsecurity.filterChain.chainMap = [
'/api/**': 'JOINED_FILTERS,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter,-rememberMeAuthenticationFilter', // Stateless chain
'/**': 'JOINED_FILTERS,-restTokenValidationFilter,-restExceptionTranslationFilter' // Traditional chain
]
grails.plugin.springsecurity.rest.login.active=true
grails.plugin.springsecurity.rest.login.failureStatusCode=401
grails.plugin.springsecurity.rest.token.validation.active=true
This is my curl command:
curl -i -X POST -H "Content-Type: application/json" -d '{"username":"xxxxx", "password":"xxxx"}' http://localhost:8080/api/login
and that's the response:
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Cache-Control: no-store
Pragma: no-cache
Content-Type: application/json;charset=UTF-8
Content-Length: 2172
Date: Tue, 01 Mar 2016 13:28:42 GMT
{"username":"xxxxxx","roles":["ROLE_ADMIN"],"token_type":"Bearer","access_token":"eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0NTY4NDI1MjIsInN1YiI6ImFkbWluZGllIiwicHJpbmNpcGFsIjoiSDRzSUFBQUFBQUFBQUpWU3YwOFVRUlIrZXg2QlNLSmdnb2tGTm1KbjloTG92RWJBMDJDV3czQmNnNGxrYnZleERqYzdzODdNSG5jTnVVb0xDZ2hJWXVLXC93SDhpalgrQWdZS1cydFkzeThFZU5JU3BkdDk4Kzczdnh4NWZ3SWpSTUJkcnhvWHhVNUhGWFBvbTFWekdCc05NYzl2ek00TTZRcHNqM3VmQUprM2c4bmdsOEFJbzhjakNrMkNMZFZoRk1CbFhWbHBiR05wcVY4T3MwdkdBY1ZPekJMZVZidnZYM0tIU2VHTkJRZTI5S2NIb09reXlNRlNadEhVb................... etc.etc.
Any help is really appreciated!
Basing on official docs you should change dataType to 'json':
dataType (default: Intelligent Guess (xml, json, script, or html))
btw did you try to remove async : false from config and check it?

Parse.com Analytics not showing

I'm trying to connect to Parse.com 's REST-API via NSURLConnection to track AppOpened metadata.
I get 200 OK back from the API and the headers are the same to the cURL headers but my API calls are not being represented in the data browser on Parse.com . Is NSURLConnection doing something silly I don't know of? API response is the same but one request gets represented while the other one isn't.
NSLog output:
<NSHTTPURLResponse: 0x7ff5eb331ca0> { URL: https://api.parse.com/1/events/AppOpened } { status code: 200, headers {
"Access-Control-Allow-Methods" = "*";
"Access-Control-Allow-Origin" = "*";
Connection = "keep-alive";
"Content-Length" = 3;
"Content-Type" = "application/json; charset=utf-8";
Date = "Sun, 04 Jan 2015 22:42:54 GMT";
Server = "nginx/1.6.0";
"X-Parse-Platform" = G1;
"X-Runtime" = "0.019842";
} }
cURL output:
HTTP/1.1 200 OK
Access-Control-Allow-Methods: *
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=utf-8
Date: Sun, 04 Jan 2015 23:03:51 GMT
Server: nginx/1.6.0
X-Parse-Platform: G1
X-Runtime: 0.012325
Content-Length: 3
Connection: keep-alive
{}
It's the same output. What am I doing wrong? Has anyone experience with this?
Turns out Parse was showing funny API keys the moment I copied them out of the cURL example they provide in their lovely docs. Don't know whose analytics I screwed over but I'm terribly sorry and it wasn't my fault!
Always copy your API keys out of [Your-Parse-App-Name]->Settings->Keys
It probably was just a stupid glitch that happened on the Server.

Resources