How can I get the cookie from a request in playframework?
I have the following test endpoint
def home = Action.async { implicit request =>
println(request)
println(request.session)
println(request.flash)
request.session.get("session") match {
case Some(cookie) => Future(Ok(cookie))
case None =>
Future(BadRequest(Json.obj("message" -> "missing session cookie")))
}
}
When submitting the following request:
curl 'http://local.example.com:9000/home' -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Connection: keep-alive' -H 'Cookie: session=eyJhbGciOiJSUzI1NiIsImtpZCI...' -H 'Upgrade-Insecure-Requests: 1' -H 'Cache-Control: max-age=0'
I unfortunately get the "missing session cookie" response. and the following printout on the console
GET /home
Session(Map())
Flash(Map())
I don't know what I'm doing wrong. Any help is much appreciated.
Edit: I set the cookie using the following method:
def tokenLogin = Action(parse.json).async { implicit request =>
val loginRequest = request.body.validate[LoginRequest]
loginRequest.fold(
errors =>
{
println(errors)
Future(BadRequest(Json.obj("message" -> JsError.toJson(errors))))
},
request => {
println("in success")
firebaseAdminService
.createSessionCookie(request.idToken)
.map(sessionCookie =>
Ok("success")
.withNewSession
.withCookies(Cookie(name = "session", value = sessionCookie))
)
}
)
}
By default, the session cookie in Play is called "PLAY_SESSION" (configuration play.http.session.cookieName).
So, you would need to use -H "Cookie: PLAY_SESSION=..." with curl.
But note, this won't work with arbitrary data since Play uses JWT and signs the information contained in the session cookie using its crypto secret.
The only thing expected to work is using a session cookie received in a Set-Cookie header from your Play service in another request to the same service (having the same secret).
update after your edit:
When using request.session, you are accessing the session cookie, which is called PLAY_SESSION and the information stored inside it.
But, you are setting a cookie of your own. This is something else.
You can access "normal" cookies with
request.cookies.get("session")
Oh, and in case you really wanted to make use of the session cookie, you can set it like this:
Ok("success").withSession("session" -> sessionCookie)
Related
Laravel Version: 9.42.0
PHP Version: 8.1.13
Database Driver & Version:
Description:
Before laravel 9 update, form rules were working as I wanted. It started behaving differently after the update.
While the same code and the same request occur without an error in laravel 8, error code 422 is returned in laravel 9.
Steps To Reproduce:
Route::post('test', function (\Illuminate\Http\Request $request) {
$request->validate([
'type' => [
'bail',
'exclude_if:type,',
'in:individual,corporate',
],
'name' => [
'bail',
'exclude_if:type,',
'required_with:type',
'min:3',
'max:49',
],
'id' => [
'bail',
'exclude_if:type,',
'required_with:type',
'digits:10',
],
'tax_office' => [
'bail',
'exclude_unless:type,corporate',
'required_if:type,corporate',
'min:2',
'max:99',
],
], $request->all());
});
Request:
curl --location --request POST 'https://site.dev/api/test' \
--header 'Accept: application/json' \
--header 'X-Requested-With: XMLHttpRequest' \
--header 'Content-Type: application/json;charset=UTF-8' \
--form 'type=""' \
--form 'name=""' \
--form 'id=""' \
--form 'tax_office=""'
Laravel 8.21.0 response status code: 200
Laravel 9.42.0 response status code: 422
Error code 422 with validation in Laravel means the request didn't pass the validation. You would have to debug it further to see which field in the payload is causing the issue by inspecting response errors.
If you got code 200 in a previous version, either you are providing it with different payload which was valid, or something changed between the two versions with the types of rules you are using.
If I had to guess I would say the problem is with the payload data you are providing, and likely before when you got code 200, you were testing with different payload or alternatively maybe you weren't using CURL to test before but instead through the browser.
You can check here to see if any of these upgrades may have had an impact: https://laravel.com/docs/9.x/upgrade
Laravel sends HTTP 422 upon a validation failure ... but, which field failed validation? And, what was the message? (check the response body).
HTTP 200 means the request succeeded — since you don't specify a return or return response() in your controller, HTTP 200 is the default response.
Your usage of 'exclude_if + required_with' seems a bit weird ... perhaps in Laravel updated the logic to fix a bug? (You might try just using required vs required_with).
I'd also try loading that request (import the CURL) into some IDE to help with debugging — Postman How to import
How to load test a Rest api post request which is having a body payload in "x-www-form-urlencoded" format
Following is my curl request -
curl --location --request POST 'https://<dns-test>/master-service/v1' \
--header 'business: Test' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'apiKey: testAPIKEY' \
--data-urlencode 'assertion=eyJraWQiOiGHJKJHGHJKJHGHJKJ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lencode 'scope=testing'```
Following is my code executing the request in Gatling -
val httpProtocol = http
.baseUrl("https://<dns-test>/master-service/v1")
.header("apiKey", "testAPIKEY")
.header("business", "test")
.header("Content-Type", "application/x-www-form-urlencoded")
.formParam("scope", "testing")
.formParam("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer")
.formParam("assertion", "eyJraWQiOiJjcnlwdC1rZXloc2dfghjkjhgfdghjklkjhgfghjkjhgnIjoiUlNBLU9BRVAtMjU2In0.g965X6rIIajOC_6t2NIlMnvJzmO50_UdJhUvOwkQwOw8nS8BhqUM0n4jf2lGNFJ7TICNUPmcPUhRmriA7R5W7ZjwLrplrDeyswmjUJAgUAv4ENDHgTdvswxtINuNvAxw99_NF4ccaOJJ6_BATTtTfOB7dmi7yxlFdAgtlWDD_biBbNx0PQ77-vXOTVVhgfdfghjhghjhghjhgijhghijhghikjhg80s174nxHTpzpvsC2S1f4DzefbarzZc-ypuXHxpwoTmi3PLLfmGZrIOTBvSHKhk23x8KFGiWLEJBe2dba1MmE_Lzwg9G5G-5qSHZtlxAbAUIDL6S_JlHqHm4ftd8rEzLRlV4ZmoE_ETeJI3cv1W_NZF31YYW81SM-bYfKlC0x0p0KLaILUjNxTcr_Cp8ydyiALNBjjXnK5IqAoLwlpQHZwh0t7yrmYFACWZRNkJQGXpqFhYO4ih-BJNBRDd5D97In90I3mM1wFP3yezRkSBNFVG7gppdKbtFalcZCkNa52RqIfJO718nNqJvmjx2zgS6VkksekeJ-_znvSC0mx-LtLA4NhNbQJJRYZFUrB4cqXYteeynXEsdhc1TBojN9FmQxxeuRrTcufXNv5qKkOu4FchvDRksx43QOHxyFBq1a6vNyTLy4wYO2gtEHM1fAo8yeoqO-N2ljUjPKlgukWal59lH_W6T-axKc1YnmvRU8VH-FAtsoI283gywghBkhOgy8ZlRRX_NV8nZEBbZmU9iyB9S1I4gnRwcxBWliqs99wVy0i6o77hPynVMqm1ghjjhghjkjhghjkjhjkjkjhLrYIeL_UmRXha07Lm-83L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n = scenario(" load test")
.exec(
http("PostRequest")
.post("/")
.check(status.in(200))
setUp(scn.inject(atOnceUsers(1)).protocols(httpProtocol))
I am getting following error:-
value formParam is not a member of io.gatling.http.protocol.HttpProtocolBuilder
The error message is pretty self explanatory: you don't define formParam on a protocol config but on an HTTP request.
Can i get okta authentication worked in Desktop applications ? Where i just want to hit okta api to get access token and other details in response ?
As per my understanding it looks for some redirect_uri which i do not have in case of desktop application. Any recommendation ?
I tried it with my web application that works fine.
with following parameters
const openIdConnectUrl = 'https://xxxx.okta.com/oauth2/default';
const clientId = 'xxxxxxxxxxxxxxxxxxx';
const redirectUri = 'http://xxxx.com/yyy/zzz';
Reqeust
curl -v -X POST \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{
"username": "xxxx#example.com",
"password": "xxxxxx",
"relayState": "/myapp/some/deep/link/i/want/to/return/to",
"options": {
"multiOptionalFactorEnroll": false,
"warnBeforePasswordExpired": false
}
}' "https://${yourOktaDomain}/api/v1/authn"
provides response like
{"expiresAt":"2019-11-13T06:27:03.000Z","status":"SUCCESS","sessionToken":"20111PJIKs504fXVoLs-9zf4t8YoVzMCEvlUbcnjDnPhqSk7C-YPzCL","_embedded":{"user":{"id":"xxxxxxxxxxxxxxx","passwordChanged":"2019-11-13T03:20:33.000Z","profile":{"login":"xxxxxx#gmail.com","firstName":"xxxx","lastName":"xxxx","locale":"en","timeZone":"America/Los_Angeles"}}},"_links":{"cancel":{"href":"https://dev-924234.okta.com/api/v1/authn/cancel","hints":{"allow":["POST"]}}}}
Refer the below documentation if needed.
https://developer.okta.com/docs/reference/api/authn
Although it did not serve my purpose completely. But it can help you.
I am performing the following POST in a Tower server:
http://<my-tower-url>/api/v2/job_templates/10/launch/
Headers:
Content-Type:application/json
Authorization:sometokenhere
And getting back the error:
{"detail":"Authentication credentials were not provided."}
Have also tried the following:
Headers:
Content-Type:application/json
Authorization:Token sometokenhere
as suggested here.
Same happens when passing raw username/password in the POST body as follows (and skipping the Authorization header):
{
"username": "myusername",
"password": "mypass",
"inventory": "inventoryname",
"verbosity": 0,
"extra_vars": {
"var1": "somevar1",
"var2": "somevar2",
"var3": "somevar3",
"var4": "somevar4",
"var5": "somevar5"
}
}
Any idea why this is not working?
Authorization: Bearer <oauth2-token-value>
See here, Section "3. OAuth 2 Token Authentication", part "Curl Example".
I ended up using basic auth as follows:
1.create the user which you want to run your ci jobs with
2.perform the following post at the respective CI job:
curl -o /dev/null -s -w \"%{http_code}\n\" -X POST http://<my-tower-url>/api/v2/job_templates/10/launch/ \
-H \"authorization: Basic $MY_AUTH_TOKEN\" \
-H \"content-type: application/json\" \
-d \"#awx_data.json
Where
awx_data.json is a file holding the actual POST body
MY_AUTH_TOKEN is the tyical base64 encoded username+password of the above user
You can also assign the above result and check it against 201 which is what AWX returns upon successful job creation.
Polling the AWX server to check if the job was successfully finished is another story of course.
I'm working on my first Sinatra app and I have an hard time getting parameters from a post request.
I'm using MiniTest::Spec and my spec looks like
payload = File.read("./spec/support/fixtures/payload.json")
post "/api/v1/verify_payload", { payload: payload }, { "CONTENT_TYPE" => "application/json" }
last_response.body.must_eql payload
And this is my route
namespace '/api/v1' do
post '/verify_payload' do
MultiJson.load(params[:payload])
end
end
The spec fails because last_response.body is empty.
Am I missing something here?
I also tried to return the entire params from verify_payload but also in that case it returned an empty string.
Update
curl -X POST -H "Content-Type: application/json" -d '{"payload":"xyz"}' http://localhost:9292/api/v1/verify_payload
does not return anything and no error on the server log
[2014-01-06 01:16:25] INFO WEBrick::HTTPServer#start: pid=10449 port=9292
127.0.0.1 - - [06/Jan/2014 01:16:27] "POST /api/v1/verify_payload HTTP/1.1" 200 6 0.0220
Thanks
Sinatra just doesn't parse this data, because they are not form parameters.
Form parameter would look like this
curl -X POST 127.1:4567/ -d "foo=bar"
Instead of params you can just use request.body.read or use rack contrib.
rack-contrib
Install it with gem install rack-contrib
require it
require 'rack'
require 'rack/contrib'
load it use Rack::PostBodyContentTypeParser
with this you can use params as normal for json post data. Something like this:
curl -X POST -H "Content-Type: application/json" -d '{"payload":"xyz"}' 127.1:4567/
source for this: Sinatra controller params method coming in empty on JSON post request, http://jaywiggins.com/2010/03/using-rack-middleware-to-parse-json/