I am using Hapi and this is my handler function:
function propertyDetailsValidateHandler(request, reply, source, error) {
console.log(request.state)
var data = joiValidationHelper.checkForErrors(request, error);
if (typeof data !== "undefined"){
return reply.view('property-details', data).code(400);
} else {
var details = request.state.details;
details.propertyType = request.payload.propertyType;
details.newBuild = request.payload.newBuild;
return reply.redirect('/property-details/postcode').state('details', details, {path: '/'});
}
}
And this is my test written using Jasmine:
describe('tell us about the property youre buying flow', function(){
it('test /property-details, status code and location', function(done){
var options = {
method: 'POST',
url: '/property-details',
headers: {
cookie: {details: { test: "test"}}
},
payload: {
propertyType: "freehold",
newBuild: true
}
};
server.inject(options, function(response){
detailsTestCookie = response.headers['set-cookie'][0].split(';')[0];
expect(response.statusCode).toBe(302);
expect(response.headers.location).toMatch("/property-details/postcode");
done();
});
});
})
The handler function runs correctly when I run my server and use the browser but when I run the test request.state is an empty object when I was expecting it to be the cookie I provided in the test hence my test fails as request.state.details is undefined. Is this the correct way to provide the headers with a cookie in my test?
This works in our project, using tape and Hapi.
var cookie = the_cookie_you_want_to_send;
Then in your test payload:
headers: { cookie: `details=${cookie}`}
The cookie needed to be encoded as that is how the cookie was registered in our server file:
server.state('details', {
ttl: null,
isSecure: false,
isHttpOnly: false,
encoding: 'base64json', //this is not encrypted just encoded
clearInvalid: false, // remove invalid cookies
strictHeader: false // don't allow violations of RFC 6265
});
Related
I'm struggling with AXIOS: it seems that my post request is not using my Cookie.
First of all, I'm creating an Axios Instance as following:
const api = axios.create({
baseURL: 'http://mylocalserver:myport/api/',
header: {
'Content-type' : 'application/json',
},
withCredentials: true,
responseType: 'json'
});
The API I'm trying to interact with is requiring a password, thus I'm defining a variable containing my password:
const password = 'mybeautifulpassword';
First, I need to post a request to create a session, and get the cookie:
const createSession = async() => {
const response = await api.post('session', { password: password});
return response.headers['set-cookie'];
}
Now, by using the returned cookie (stored in cookieAuth variable), I can interact with the API.
I know there is an endpoint allowing me to retrieve informations:
const readInfo = async(cookieAuth) => {
return await api.get('endpoint/a', {
headers: {
Cookie: cookieAuth,
}
})
}
This is working properly.
It's another story when I want to launch a post request.
const createInfo = async(cookieAuth, infoName) => {
try {
const data = JSON.stringify({
name: infoName
})
return await api.post('endpoint/a', {
headers: {
Cookie: cookieAuth,
},
data: data,
})
} catch (error) {
console.log(error);
}
};
When I launch the createInfo method, I got a 401 status (Unauthorized). It looks like Axios is not using my cookieAuth for the post request...
If I'm using Postman to make the same request, it works...
What am I doing wrong in this code? Thanks a lot for your help
I finally found my mistake.
As written in the Axios Doc ( https://axios-http.com/docs/instance )
The specified config will be merged with the instance config.
after creating the instance, I must follow the following structure to perform a post requests:
axios#post(url[, data[, config]])
My requests is working now :
await api.post('endpoint/a', {data: data}, {
headers: {
'Cookie': cookiesAuth
}
});
I'm trying to pass JWT token and data fields via Jquery and then consume those values in Flask.
So, my client side query looks like this:
function getData() {
var data = {
UserPoolId : 'AWS CognitoUser Pool Id',
ClientId : 'AWS CognitoUser client Id'
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(data);
var cognitoUser = userPool.getCurrentUser();
cognitoUser.getSession(function(err, session) {
if (err) {
alert(err);
return;
}
console.log('session validity: ' + session.isValid());
console.log(cognitoUser.signInUserSession.accessToken.jwtToken);
//
$.ajax({
url: "/api/v1/count",
type: "POST",
headers: { "X-Test-Header": cognitoUser.signInUserSession.accessToken.jwtToken },
// data: JSON.stringify(data),
data: JSON.stringify("{'UserPoolId': 'XXXX','ClientId': 'XXXX'}"),
contentType: 'application/json; charset=utf-8',
error: function(err) {
switch (err.status) {
case "400":
// bad request
break;
case "401":
// unauthorized
break;
case "403":
// forbidden
break;
default:
//Something bad happened
break;
}
},
success: function(data) {
console.log(data);
}
});
//
});
}
Now, in my serverside flask:
I tried to catch the token value using below: which is not working
#app.route("/api/v1/count", methods=["GET", "POST"])
def get_data_count():
if 'X-Test-Header' in request.headers:
headers = request.headers
app.logger.info(headers)
auth = headers.get("X-Test-Header")
app.logger.info('testing info log' + auth)
Also I tried to catch the data fields , using result = request.get_json() also not working.
I tried to inspect in chrome, and I don't see these values being added to the request header.
Can anyone suggest to me if I'm doing it correctly while passing the values from client to server? I also don't see console.log(cognitoUser.signInUserSession.accessToken.jwtToken) in the console log.
if not can anyone suggest to me, how to fix it?
TL;DR
How do I intercept a request, ping a different route for an ID, store the ID in a session, then continue the original request (especially PUT/POST with payloads) using the ID I just got?
Background
I am using HapiJS (8) to proxy requests from the client to an existing API (where I have no control over processes/logic). The API requires each request to contain a 'session ID' in either the query string or the payload (depending on the http method). In order to get a session ID, all I have to do is ask for one... there is no username/pwd required (it uses Basic auth in the headers). The session ID expires every 24 hours if it isn't renewed. Each client has their own session ID.
I am currently using hapi-auth-cookie to store the value of the session ID which gets queried when the ID is needed. If the ID is expired or null, I need to request a new one before the client's request can be successfully proxy'd to the API.
Current Solution
When the client's request method is 'GET', I am handling this challenge quite gracefully utilizing the appendNext configuration described in the hapi-auth-cookie docs. The request is intercepted by hapi-auth-cookie, if a new session ID is needed, a request is sent to that particular route to get it, the API returns the ID which is then assigned to the Hapi session, and then (using Wreck) a reply.redirect returns to the original GET request where it completes. Seamless and graceful.
However, I cannot figure out how to accomplish this same flow with different http methods that contain payloads of data.
Is there something besides reply.redirect that will accomplish the same goal while maintaining original payloads and methods? Or is there a much better way to do this in general?
The Code (for what currently works for 'GET' requests)
main app file (hapi-auth-cookie configs)
# register plugins
server.register require('./plugins')
, (err) ->
throw err if err
# set authentication (NLS) configs
server.auth.strategy 'session', 'cookie',
password: 'session_pwd'
cookie: 'ghsid'
redirectTo: '/api/SessionID' #get new session ID
isSecure: config.get 'ssl'
appendNext: true
ttl: config.get 'session_length'
Controller that leverages session authentication and invokes hapi-auth-cookie plugin:
simpleRequest:
auth: 'session'
handler: (request, reply) ->
qs = Qs.stringify request.query
request.papi_url = "/api/route/sample?#{qs}"
reply.proxy
mapUri: (request, reply) ->
auth = config.get 'basic_auth'
api_host = config.get 'api_host'
papi_url = request.papi_url
path = api_host + papi_url
next null, path, {authorization: auth}
Route for getting a new session ID
module.exports = [
{
path: '/api/SessionID'
method: 'GET'
config: SessionController.session
}
]
Session Controller
Wreck = require 'wreck'
config = require 'config'
module.exports =
session:
description: 'Get new session ID'
auth:
mode: 'try'
strategy: 'session'
plugins:
'hapi-auth-cookie':
redirectTo: false
handler: (request, reply) ->
# request configs
papi_url = "/Session"
api_host = config.get 'api_host'
url = api_host + papi_url
opts =
headers:
'Authorization': config.get 'basic_auth'
'content-type': 'application/json;charset=UTF-8'
# make request to PAPI
Wreck.post url, opts, (err, res, body) ->
throw new Error err if err
try
bdy = JSON.parse body
sess =
nls: bdy.SessionId
if bdy.SessionId
# authenticate user with NLS
request.auth.session.set sess
# redirect to initial route
reply.redirect request.url.query.next
else
return throw new Error
catch err
throw new Error err
Final solution
Based on Matt Harrison's answer, I created a custom plugin that gets registered as an authentication scheme so I can control this per route.
Here's the plugin code:
Wreck = require 'wreck'
config = require 'config'
exports.register = (server, options, next) ->
server.auth.scheme 'cookie', internals.implementation
next()
exports.register.attributes =
name: 'Hapi Session Interceptor'
version: '1.0.0'
internals = {}
internals.implementation = (server, options, next) ->
scheme = authenticate: (request, reply) ->
validate = ->
session = request.state.sessionID
unless session
return unauthenticated()
reply.continue(credentials: {'session': session})
unauthenticated = ->
api_url = "/SessionID"
api_host = config.get 'api_host'
url = api_host + api_url
opts =
headers:
'Authorization': config.get 'basic_auth'
'content-type': 'application/json;charset=UTF-8'
# make request to API
Wreck.post url, opts, (err, res, body) ->
throw new Error err if err
bdy = JSON.parse body
sess =
session: bdy.SessionId
if bdy.SessionId
reply.state 'sessionID', bdy.SessionId
reply.continue(credentials: sess)
else
return throw new Error
validate()
return scheme
Although not entirely faithful to your code, I've put together an example that has all the pieces I think you're working with.
I've made a service plugin to represent your API. The upstream plugin represents the actual upstream API you're proxying to.
All requests passthrough the service and are proxied to the upstream, which just prints out all of the headers and payload it received.
If the original request doesn't contain a cookie with a sessionId, a route is hit on the upstream to get one. A cookie is then set with this value when the response comes back down stream.
The code is here: https://github.com/mtharrison/hapijs-proxy-trouble
Try it out with curl and your browser.
GET: curl http://localhost:4000
POST W/PAYLOAD: curl -X POST -H "content-type: application/json" -d '{"example":"payload"}' http://localhost:4000
index.js
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 4000, labels: ['service'] }); // Your service
server.connection({ port: 5000, labels: ['upstream']}); // Pretend upstream API
server.state('session', {
ttl: 24 * 60 * 60 * 1000,
isSecure: false,
path: '/',
encoding: 'base64json'
});
server.register([{
register: require('./service')
}, {
register: require('./upstream')
}],
function (err) {
if (err) {
throw err;
}
server.start(function () {
console.log('Started!');
});
});
service.js
var Wreck = require('wreck');
exports.register = function (server, options, next) {
// This is where the magic happens!
server.select('service').ext('onPreHandler', function (request, reply) {
var sessionId = request.state.session;
var _done = function () {
// Set the cookie and proceed to the route
request.headers['X-Session-Id'] = sessionId;
reply.state('session', sessionId);
reply.continue();
}
if (typeof sessionId !== 'undefined')
return _done();
// We don't have a sessionId, let's get one
Wreck.get('http://localhost:5000/sessionId', {json: true}, function (err, res, payload) {
if(err) {
throw err;
}
sessionId = payload.id;
_done();
});
});
server.select('service').route({
method: '*',
path: '/{p*}', // Proxies all routes and methods
handler: {
proxy: {
host: 'localhost',
port: 5000,
protocol: 'http',
passThrough: true
}
}
});
next();
};
exports.register.attributes = {
name: 'your-service'
};
upstream.js
exports.register = function (server, options, next) {
server.select('upstream').route([{
method: '*',
path: '/{p*}',
handler: function (request, reply) {
// Just prints out what it received for headers and payload
// To prove we got send the original payload and the sessionID header
reply({
originalHeaders: request.headers,
originalPayload: request.payload,
})
}
}, {
method: 'GET',
path: '/sessionId',
handler: function (request, reply) {
// Returns a random session id
reply({ id: (Math.floor(Math.random() * 1000)) });
}
}]);
next();
};
exports.register.attributes = {
name: 'upstream'
};
I must confess I'm stuck. I need a nodejs app to download a file from a SharePoint library. Simple, huh? No. Not the simple OOTB SharePoint. The only-ssl allowed, with specific mandatory header added and surely only domain-based NTLM authentication method.
I've tried httpntlm (https://www.npmjs.org/package/httpntlm) that seemed to just might work in advance, but no. The SP responses with something went wrong message.
I've tried node-sharepoint, but it doesn't support NTLM yet. The app gets ETIMEDOUT response.
Any ideas, please welcome.
I am able to download the file using httpntlm module.you need to change the few lines of code.Replace the waterfall logic with below code in httpntlm.js.
async.waterfall([
function ($){
var type1msg = ntlm.createType1Message(options);
httpreq.get(options.url, {
headers:{
'Connection' : 'keep-alive',
'Authorization': type1msg
},
agent: keepaliveAgent
}, $);
},
function (res, $){
if(!res.headers['www-authenticate'])
return $(new Error('www-authenticate not found on response of second request'));
var type2msg = ntlm.parseType2Message(res.headers['www-authenticate']);
var type3msg = ntlm.createType3Message(type2msg, options);
if(method!=='download'){
httpreq[method](options.url, {
headers:{
'Connection' : 'Close',
'Authorization': type3msg
},
allowRedirects: false,
agent: keepaliveAgent
}, $);
}else{
//By Dheeraj for file download
httpreq.download(
url,
{
headers:{
'Connection' : 'Close',
'Authorization': type3msg
},
//allowRedirects: false,
agent: keepaliveAgent
},
__dirname + 'your_filename',
function (err, progress){
if (err) return console.log(err);
console.log(progress);
}, function (err, res){
if (err) return console.log(err);
console.log(res);
});
}
}
], callback);
};
['get', 'put', 'post', 'delete', 'head','download'].forEach(function(method){
exports[method] = exports.method.bind(exports, method);
});
and replace download method of httpreq.js(httpntm_module/node_modules/httpreq_module/httpreq.js) You can find it at Line number 79 approx.
exports.download = function (url,options, downloadlocation, progressCallback, callback) {
//var options = {};
options.url = url;
options.method = 'GET';
options.downloadlocation = downloadlocation;
options.allowRedirects = true;
// if only 3 args are provided, so no progressCallback
if(callback === undefined && progressCallback && typeof(progressCallback)==="function")
callback = progressCallback;
else
options.progressCallback = progressCallback;
doRequest(options, callback);
}
Please let me know if you are still getting issues.
Hi I am student of Computer Science and doing some experiments on oauth.io. but i am facing problem to get refresh_token after getting code successfully. After getting the code i am writing the follwing line of code but its giving me Internal server error..
The code is
$.ajax("https://oauth.io/auth/access_token", {
type: "post",
data: {
code: result.code,
key: '5WeOrrR3tP6RyShR1',
secret: '2_q3tb_D_qgDwSGpt' },
success: function (data) {
console.log("result", data);
}
});
Which url used to get refresh_token? please someone help me.
thanks
there was a bug recently in the js sdk when you set the response type server-side (to get the code & refresh_token), so you may have to redownload oauth.js if you use a static version.
I guess your jquery code is server side (because of the nodejs tag and the use of a code), but i had an error "no transport" that i fixed with a new XMLHttpRequest. Here is my full test:
var jsdom = require('jsdom').jsdom;
var win = jsdom().createWindow();
var $ = require('jquery')(win);
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
$.support.cors = true;
$.ajaxSettings.xhr = function () {
return new XMLHttpRequest;
}
$.ajax("https://oauth.io/auth/access_token", {
type: "post",
data: {
code: process.argv[2],
key: 'xxxxxxxxxxxx',
secret: 'yyyyyyyyyyyy' },
success: function (data) {
console.log("result", data);
},
error: function() {
console.error(arguments);
}
});
and my result looks like:
{ access_token: 'xxxxxxxxxxx',
request:
{ url: '{{instance_url}}',
required: [ 'instance_url' ],
headers: { Authorization: 'Bearer {{token}}' } },
refresh_token: 'yyyyyyyyyyyyy',
id: 'https://login.salesforce.com/id/00Db0000000ZbGGEA0/005b0000000SSGXAA4',
instance_url: 'https://eu2.salesforce.com',
signature: 'zzzzzzzzzzzzz',
state: 'random_string',
provider: 'salesforce' }