Add custom session data to jsoup POST request in clojure - testing

I am testing my first clojure ring application with midje and jsoup.
The app uses ring-session to add session for logged-only pages.
Session is not a cookie, neither part of the header of the request and I dont know how to add it to perform a post request correctly on logged pages...
A POST request in jsoup is something like:
(-> (Jsoup/connect "http://localhost:3001/sendto")
(.userAgent "...")
(.header "Content-Type","application/x-www-form-urlencoded")
(.data "amount" amount)
(.data "to" email)
(.data "sendto-submit" "Send")
(.post))
Altough this will not work when trying to perform a request against a logged-only url.
I'd have to add the session object, that in my case is something like:
{:session {:auth {:email "name#email.com"}}}
to the request, but so far neither (.cookie) nor (.data) worked...
Any help is suuuuper welcome :)

Without knowing the server side config, it's hard to give exact advice, but you have to remember the cookie you get on login and send it with the requests.
What you see on the server as {:session {:auth ,,,}} is the result of the session wrapper loading server side stored data into the request.
So basically:
you send a request, that starts a session (e.g. your login)
the server sends you a cookie back and stores informations about the login in it's session storage
you send a request, that includes that cookie
the server looks the cookie up in the session storage and injects the data associated with it in the request.
See the source/doc

Related

RESTDataSource - How to know if response comes from get request or cache

I need to get some data from a REST API in my GraphQL API. For that I'm extending RESTDataSource from apollo-datasource-rest.
From what I understood, RESTDataSource caches automatically requests but I'd like to verify if it is indeed cached. Is there a way to know if my request is getting its data from the cache or if it's hitting the REST API?
I noticed that the first request takes some time, but the following ones are way faster and also, the didReceiveResponse method is not called everytime I make a query. Is it because the data is loaded from the cache?
I'm using apollo-server-express.
Thanks for your help!
You can time the requests like following:
console.time('restdatasource get req')
this.get(url)
console.timeEnd('restdatasource get req')
Now, if the time is under 100-150 milliseconds, that should be a request coming from the cache.
You can monitor the console, under the network tab. You will be able to see what endpoints the application is calling. If it uses cached data, there will be no new request to your endpoint logged
If you are trying to verify this locally, one good option is to setup a local proxy so that you can see all the network calls being made. (no network call meaning the call was read from cache) Then you can simply configure your app using this apollo documentation to forward all outgoing calls through a proxy like mitmproxy.

Same response data for all iterations even though cookie is cleared

My Test structure in Jmeter
Thread group (2 users)
Http request
Listener
For each iteration same form_key values are getting in response which should not be.
How to get unique form_key in response for each iteration
Jmeter Test result screenshot
I cannot reproduce your issue using one of the online Magento demo instances, in particular this one: http://demo-acm-2.bird.eu/customer/account/login/
As you can see, each time form_key is different for each user for each iteration.
If you're using HTTP Cookie Manager - make sure to tick "Clear cookies each iteration" box
Also make sure to properly setup the HTTP Request sampler, to wit put http or https into "Protocol", server name or IP to the relevant field, path, etc.

Ember.js Authentication Token for Ember-Data + AMS => JSON or HTTP Header?

CONTEXT:
I have an Ember.js 1.1.0-beta.1 application that exchanges JSON data with a Rails-API server (Rails 4). JSON data exchange is accomplished with Ember-Data 1.0.0-beta.2 and Active Model Serializers 0.8.1 (AMS). I'm using the default recommended configurations for both Ember-Data and AMS, and am compliant with the JSON-API spec.
On any given RESTful call, the client passes the current authentication token to the server. The authentication token is verified and retired, and a new authentication token is generated and sent back to the client. Thus, every RESTful call accepts an authentication token in the request, and provides a new authentication token in the response that the client can cache and use for the next RESTful call.
QUESTION:
Where do I put the authentication token in each request and response?
Should it be part of each object's JSON in request and response? If so, where is the token placed in the existing object's JSON structure (which has nothing to do with authentication)?
Or should they be placed in the HTTP header for each request and response object?
What is "The Ember Way" that one might eventually expect to find in the new Ember Guides Cookbook?
MORE CONTEXT:
I'm already familiar with the following links:
#machty 2 Embercasts: http://www.embercasts.com/episodes/client-side-authentication-part-2
#wycats tweet: https://twitter.com/wycats/status/376495062709854209
#cavneb 3 blog posts: http://coderberry.me/blog/2013/07/08/authentication-with-emberjs-part-1
#simplabs blog post: http://log.simplabs.com/post/53016599611/authentication-in-ember-js
...and am looking for answers that go beyond these, and are specific to Ember-Data + AMS.
With the exception of the need to pass a new token back to the client in the response via Ember-Data, assume my client code is otherwise similar to the #machty Embercast example on GitHub: https://github.com/embercasts/authentication-part-2/blob/master/public/js/app.js
Thank you very much!
I've got a similar stack - ember, ember-data and rails-api with AMS. Right now, I'm just passing the authentication token (which I store in localStorage) in a header (though you could pass it on the query string) by modifying the RESTAdapter's ajax method.
My initial thought would be to avoid resetting the token on every request. If you're particularly concerned about the token being sniffed, it might be easier to just reset the token on the server at a regular interval (say, 10 minutes). Then, if any request from the client fails due to an old token, just fetch the new token (by passing a'reset token' that your server gives you at login) and replay the initial request.
As for where to put the token, there isn't really an "Ember Way" - I prefer passing it in a header since passing it in the query string can mess with caching and is also more likely to be logged somewhere along the way. I'd definitely avoid passing it in the request body - that would go against what ember-data expects, I'd imagine.
I have built something similar, although I do not reset the token unless the user signs out.
I would not put it in the request body itself - you are just going to pollute your models. There probably is no Ember way since this is more of a transport issue. I pass the token using a custom HTTP header and/or a cookie. The cookie is needed to authorize file downloads, which can not be done through ajax, although the cookie works for ajax calls too. In your case I would use a cookie and have the server set it to the new value each time. However, your scheme of resetting the token on each JSON request is not going to work on simultaneous requests. Is this really necessary? If you use TLS you probably don't need to worry so much. You could also timeout the token so that if there are no requests for 10 minutes a new token is generated.

is possible to keep session alive using NSURLConnection doing different requests?

I am using NSRULConnection to make http request on my iphone application. All works just fine.
The problem is after logged in I need to keep the same session to get data from the server.
I read a few posts saying all I need was using the same instance of NSURLConnection and it would use the same session... if that is true, that doesn't make sense to me, cause the NSURLConnection is not mutable and there is no method to change the request since I have to access different pages.
Is there anyway simple way to keep a session using NSURLConnection.
If you are managing sessions using cookies, there is no need to do anything special to achieve session management.The URL loading system automatically sends any stored cookies appropriate for an NSURLRequest. unless the request specifies not to send cookies. So, your sessions should be managed automatically for you.
However, as the Apple's doc says, if someone has set the cookie-acceptance policy to reject all cookies or only accept cookies selectively, you might be in a fix (you can change the cookie acceptance policy yourself too). In such a case, you might resort to URL based session-management; in which you append a session-identifier to the URL as a parameter (You can get this identifier as a part of the successful log-in response), which can be extracted on the server-side. This, however, is considered really bad practice.
Another way, which I have come across more often, is to get a session-identifier as part of the response for a successful log-in and include that identifier in all your subsequent requests as a parameter. Although this would require a major change in the way the server handles the sessions.

What method should I use for a login (authentication) request?

I would like to know which http method I should use when doing a login request, and why? Since this request creates an object (a user session) on the server, I think it should be POST, what do you think? But since the login request should be idempotent, it could be PUT, couldn't it?
Same question for a logout request, should I use the DELETE method?
If your login request is via a user supplying a username and password then a POST is preferable, as details will be sent in the HTTP messages body rather than the URL. Although it will still be sent plain text, unless you're encrypting via https.
The HTTP DELETE method is a request to delete something on the server. I don't think that DELETING an in memory user session is really what it's intended; more it's for deleting the user record itself. So potentially logout can be just a GET e.g. www.yoursite.com/logout.
I believe that you can translate LOGIN & LOGOUT methods into basic CRUD operations CREATE & DELETE. Since you are creating a new resource called SESSION and destroying it when logging out:
POST /login - creates session
DELETE /logout - destroys session
I would never do LOGOUT as GET just because anyone could make an attack just simply by sending an email with IMG tag or link to website where such an IMG tag exists. (<img src="youtsite.com/logout" />)
P.S.
Long time I was wondering how would you create a RESTful login/logout and it turned out it's really simple, you do it just like I described: use /session/ endpoint with CREATE and DELETE methods and you are fine. You could also use UPDATE if you want to update session in one way or another...
Here is my solution based on REST guides and recommendations:
LOGIN - create a resource
Request:
POST => https://example.com/sessions/
BODY => {'login': 'login#example.com', 'password': '123456'}
Response:
http status code 201 (Created)
{'token': '761b69db-ace4-49cd-84cb-4550be231e8f'}
LOGOUT - delete a resource
Request:
DELETE => https://example.com/sessions/761b69db-ace4-49cd-84cb-4550be231e8f/
Response:
http status code 204 (No Content)
For login request we should use POST method. Because our login data is secure which needs security. When use POST method the data is sent to server in a bundle. But in GET method data is sent to the server followed by the url like append with url request which will be seen to everyone.
So For secure authentication and authorization process we should use POST method.
I hope this solution will help you.
Thanks
Regarding the method for logging out:
In the Spring (Java Framework) documentation, they state that a POST request is preferred, since a GET makes you vulnerable to CSRF (Cross-Site Request Forgery) and the user could be logged out.
Adding CSRF will update the LogoutFilter to only use HTTP POST. This ensures that log out requires a CSRF token and that a malicious user cannot forcibly log out your users.
See: https://docs.spring.io/spring-security/site/docs/current/reference/html/web-app-security.html#csrf-logout
Logging in should also use POST (body can be encrypted, see the other answers).
For Login I use POST, below is my code for LOGIN method
I used Nodejs with Express and Mongoose
your router.js
const express = require("express");
const router = express.Router();
router.post("/login", login);
your controller.js
export.login = async(req, res) => {
//find the user based on email
const {email, password} = req.body;
try{
const user = awaitUser.findOne({email});
if(user==null)
return res.status(400).json({err : "User with
email doesnot exists.Please signup"});
}
catch(error){
return res.status(500).json({err :
error.message});
}
//IF EVERYTHING GOES FINE, ASSIGN YOUR TOKEN
make sure you have JWT installed
const token = jwt.sign({_id: user._id}, YOUR_SECRET_KEY);
res.cookie('t');
const {_id, name, email} = user;
return res.json({token, user : {_id, email, name}});
}