How to get and use Rundeck JSESSIONID - rundeck

I am trying to get the a valid session id but so far with no success.
I am trying to work with the rundeck API, with password authentication:
To submit authentication, submit a POST request to the URL:
$RUNDECK_SERVER_URL/j_security_check
With these parameters:
j_username: rundeck username j_password: password
Like the docs suggest, I am running:
>>> import request
>>> jsessionid = requests.post("http://localhost:4440/j_security_check", data=
{"j_username": "admin", "j_password": "admin" },
allow_redirects=False).cookies['JSESSIONID']
Resulting the log:
09/04/2017 03:22:59 PM - DEBUG - Starting new HTTP connection (1):
10.200.101.21
09/04/2017 03:22:59 PM - DEBUG - http://localhost:4440 "POST
/j_security_check?j_username=admin&j_password=admin HTTP/1.1" 302 0
But the jsessionid is never valid for the next api calls, for example:
>>> response = requests.post("http://localhost:4440/api/14/project/my_project/hi
story" , headers={ "Content-Type": 'application/xml', 'X-Rundeck-
Auth-Token': jsessionid })
>>> response.content
"<result error='true' apiversion='20'><error code='unauthorized'>
<message>(Token:lhefo****) is not authorized for: /api/14/project/weekly_builds/history</message></error></result>"
However, if for jsessionid I am using the token I can see in the Rundeck UI (in http://localhost:4440/user/profile), then the API call works good and I get the history.
Any ideas of what I am doing wrong? Or what I am missing?
Thanks.

Don't worry about the JSESSIONID. You should use requests.Seesion()
import requests
s = requests.Session()
r = s.post("URL:PORT/j_security_check", data={"j_username": "user", "j_password": "pass"})
r.status_code # this should be 200
r.url # this should be rundeck home
r = s.get("URL:PORT/api/11/projects",headers = {'Accept': 'application/json'})
r.json() # you should see all your project

Related

How to check for proper format in my API response

Currently running tests for my REST API which:
takes an endpoint from the user
using that endpoint, grabs info from a server
sends it to another server to be translated
then proceeds to jsonify the data.
I've written a series of automated tests running and I cannot get one to pass - the test that actually identifies the content of the response. I've tried including several variations of what the test is expecting but I feel it's the actual implementation that's the issue. Here's the expected API response from the client request:
{ "name": "random_character", "description": "Translated description of requested character is output here" }
Here is the testing class inside my test_main.py:
class Test_functions(unittest.TestCase):
# checking if response of 200 is returned
def test_healthcheck_PokeAPI(self):
manualtest = app.test_client(self)
response = manualtest.get("/pokemon/")
status_code = response.status_code
self.assertEqual(status_code, 200)
# the status code should be a redirect i.e. 308; so I made a separate test for this
def test_healthcheck_ShakesprAPI(self):
manualtest = app.test_client(self)
response = manualtest.get("/pokemon/charizard")
self.assertEqual(response.status_code, 308)
def test_response_content(self):
manualtest = app.test_client(self)
response = manualtest.get("/pokemon/charizard")
self.assertEqual(response.content_type,
'application/json') <<<< this test is failing
def test_trans_shakespeare_response(self):
manualtest = app.test_client(self)
response = manualtest.get("/pokemon/charizard")
self.assertFalse(b"doth" in response.data)
Traceback:
AssertionError: 'text/html; charset=utf-8' != 'application/json' - text/html; charset=utf-8 + application/json
Any help would be greatly appreciated

Connecting to Facebook's API

I am facing this issue connecting with Facebook's API using httr package, while testing on 'me' node I came along the following problem.
I was under the impression that me node does not require special permissions.
Testing on the browser with 'https://graph.facebook.com/me' gave the same results, it would be great if some one could provide an explanation.
# Define keys
app_id = 'my_app_id'
app_secret = 'my_app_secret'
# Define the app
fb_app <- oauth_app(appname = "facebook",
key = app_id,
secret = app_secret)
# Get OAuth user access token
fb_token <- oauth2.0_token(oauth_endpoints("facebook"),
fb_app,
scope = 'public_profile',
type = "application/x-www-form-urlencoded",
cache = TRUE)
response <- GET("https://graph.facebook.com",
path = "/me",
config = config(token = fb_token))
# Show content returned
content(response)
$error
$error$message
[1] "An active access token must be used to query information about the current user."
$error$type
[1] "OAuthException"
$error$code
[1] 2500
$error$fbtrace_id
[1] "ARRnb93rZHmWLlXK_MMJlfi"
Noting that I have signed in using the app.

getting NoAuthorization Header Missing Exception while using flask-jwt-extended

When I try this example and if the jet token is not provided by header I get error:
{
"msg": "Missing cookie \"access_token_cookie\""
}
example:
from flask import Flask, jsonify, request
from flask_jwt_extended import (
JWTManager, jwt_required, create_access_token,
jwt_refresh_token_required, create_refresh_token,
get_jwt_identity, set_access_cookies,
set_refresh_cookies, unset_jwt_cookies
)
from flask_jwt_extended.config import config
# NOTE: This is just a basic example of how to enable cookies. This is
# vulnerable to CSRF attacks, and should not be used as is. See
# csrf_protection_with_cookies.py for a more complete example!
app = Flask(__name__)
# Configure application to store JWTs in cookies. Whenever you make
# a request to a protected endpoint, you will need to send in the
# access or refresh JWT via a cookie.
app.config['JWT_TOKEN_LOCATION'] = ['cookies']
# Set the cookie paths, so that you are only sending your access token
# cookie to the access endpoints, and only sending your refresh token
# to the refresh endpoint. Technically this is optional, but it is in
# your best interest to not send additional cookies in the request if
# they aren't needed.
app.config['JWT_ACCESS_COOKIE_PATH'] = '/api/'
app.config['JWT_REFRESH_COOKIE_PATH'] = '/token/refresh'
# Disable CSRF protection for this example. In almost every case,
# this is a bad idea. See examples/csrf_protection_with_cookies.py
# for how safely store JWTs in cookies
app.config['JWT_COOKIE_CSRF_PROTECT'] = False
# Set the secret key to sign the JWTs with
app.config['JWT_SECRET_KEY'] = 'super-secret' # Change this!
jwt = JWTManager(app)
# Use the set_access_cookie() and set_refresh_cookie() on a response
# object to set the JWTs in the response cookies. You can configure
# the cookie names and other settings via various app.config options
#app.route('/token/auth', methods=['POST'])
def login():
# username = request.json.get('username', None)
# password = request.json.get('password', None)
# if username != 'test' or password != 'test':
# return jsonify({'login': False}), 401
# print dir(config)
# Create the tokens we will be sending back to the user
access_token = create_access_token(identity="test")
refresh_token = create_refresh_token(identity="test")
# Set the JWT cookies in the response
resp = jsonify({'login': True, "cookie_key": config.access_cookie_name, "cooke_value": access_token})
set_access_cookies(resp, access_token)
set_refresh_cookies(resp, refresh_token)
return resp, 200
# Same thing as login here, except we are only setting a new cookie
# for the access token.
#app.route('/token/refresh', methods=['POST'])
#jwt_refresh_token_required
def refresh():
# Create the new access token
current_user = get_jwt_identity()
access_token = create_access_token(identity=current_user)
# Set the JWT access cookie in the response
resp = jsonify({'refresh': True})
set_access_cookies(resp, access_token)
return resp, 200
# Because the JWTs are stored in an httponly cookie now, we cannot
# log the user out by simply deleting the cookie in the frontend.
# We need the backend to send us a response to delete the cookies
# in order to logout. unset_jwt_cookies is a helper function to
# do just that.
#app.route('/token/remove', methods=['POST'])
def logout():
resp = jsonify({'logout': True})
unset_jwt_cookies(resp)
return resp, 200
# We do not need to make any changes to our protected endpoints. They
# will all still function the exact same as they do when sending the
# JWT in via a header instead of a cookie
#app.route('/api/example', methods=['GET'])
#jwt_required
def protected():
username = get_jwt_identity()
return jsonify({'hello': 'from {}'.format(username)}), 200
if __name__ == '__main__':
app.run(debug=True)
But in my office I have similar setup except I am not calling
username = get_jwt_identity()
I get NoAuthorization exception get raised.
how does this work ...
It's mean you not login and flask-jwt can't find any token on your cookies.
Do you login before call this resource?
check your cookie that returned from app.
In my case it was CORS error, I was using a different api address from the website

Sending auth cookie using WS and ScalaTest

I have a web app which uses a form to login, this returns a session cookie to the user which is used to authorize requests to the rest of the app. I'm having trouble sending this cookie value with my requests. My test harness is below:
val loginResponse = await(WS.url(s"http://localhost:$port/authenticate")
.withHeaders("Content-Type" -> "application/x-www-form-urlencoded")
.post(Map("email" -> Seq("admin#example.com"), "password" -> Seq("genivirocks!"))))
loginResponse.status mustBe (OK)
val cookies = loginResponse.cookies(0).toString
val vehiclesResponse = await(WS.url(s"http://localhost:$port/api/v1/vehicles/" + testVin)
.withHeaders("Cookie" -> cookies)
.put(""))
vehiclesResponse.status mustBe (OK)
val vehiclesFilterResponse = await(WS.url(s"http://localhost:$port/api/v1/vehicles?regex=" + testVin)
.withHeaders("Cookie" -> cookies)
.get())
vehiclesFilterResponse.status mustBe (OK)
The request fails, as the second request gets a 204 instead of a 200, as it gets redirected to the login page because the cookie is interpreted as invalid. The web server gives the following error, when the second request is made:
2015-10-06 14:56:15,991
[sota-core-service-akka.actor.default-dispatcher-42] WARN
akka.actor.ActorSystemImpl - Illegal request header: Illegal 'cookie'
header: Invalid input 'EOI', expected tchar, '\r', WSP or '=' (line 1,
column 178):
PLAY2AUTH_SESS_ID=ee84a2d5a0a422a3e5446f82f9f3c6f8eda9db1cr~jz7ei0asg0hk.ebd8j.h4cpjj~~9c0(yxt8p*jqvgf)_t1.5b(7i~tly21(*id;
path=/; expires=1444139775000; maxAge=3600s; HTTPOnly
I've tried building the cookie string myself and making sure there are no extra '\r' characters at the end and so on, with no luck. Google also doesn't seem to have any hints. Is there a better way of sending cookie values using WS?
EDIT
Got it working with the following code:
import play.api.mvc.Cookies
val loginResponse = ...
loginResponse.status mustBe (OK)
val cookies = loginResponse.cookies
val cookie = Cookies.decodeCookieHeader(loginResponse.cookies(0).toString)
val vehiclesResponse = await(WS.url(s"http://localhost:$port/api/v1/vehicles/" + testVin)
.withHeaders("Cookie" -> Cookies.encodeCookieHeader(cookie))
.put(""))
vehiclesResponse.status mustBe (OK)
...
Why don't you use the existing Cookies.encode function to do the cookie encoding for you?
import play.api.mvc.Cookies
val loginResponse = ...
loginResponse.status mustBe (OK)
val cookies = loginResponse.cookies
val vehiclesResponse = await(WS.url(s"http://localhost:$port/api/v1/vehicles/" + testVin)
.withHeaders("Cookie" -> Cookies.encode(cookies))
.put(""))
vehiclesResponse.status mustBe (OK)
...

How to log in to a website with urllib?

I am trying to log on this website: http://www.broadinstitute.org/cmap/index.jsp. I am using python 3.3 on Windows. I followed this answer https://stackoverflow.com/a/2910487/651779. My code:
import http.cookiejar
import urllib
url = 'http://www.broadinstitute.org/cmap/index.jsp'
values = {'j_username' : 'username',
'j_password' : 'password'}
data = urllib.parse.urlencode(values)
binary_data = data.encode('ascii')
cookies = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(
urllib.request.HTTPRedirectHandler(),
urllib.request.HTTPHandler(debuglevel=0),
urllib.request.HTTPSHandler(debuglevel=0),
urllib.request.HTTPCookieProcessor(cookies))
response = opener.open(url, binary_data)
the_page = response.read()
http_headers = response.info()
It runs without erros, however the html in the_page is just the log in page. How can I log onto this page?
The site is using a JSESSIONID cookie to create session since HTTP requests are stateless. When you're making your request, you're not getting that session id first.
I sniffed a session to log into that site using Fiddler and found that the POST is made to a different URL, but it has that JSESSIONID cookie set. So you need to make a get to the URL first, capture that cookie using the cookiehandler, then POST to this URL:
post_url = 'http://www.broadinstitute.org/cmap/j_security_check'
You don't need to save the HTTP GET request at all, you can simply call opener.open(url), then in your code change the response line to this:
response = opener.open(post_url, binary_data)
Also the payload was missing the submit method. Here's the whole thing with the changes I suggest:
import http.cookiejar
import urllib
get_url = 'http://www.broadinstitute.org/cmap/index.jsp'
post_url = 'http://www.broadinstitute.org/cmap/j_security_check'
values = urllib.parse.urlencode({'j_username': <MYCOOLUSERNAME>,
'j_password': <MYCOOLPASSSWORD>,
'submit': 'sign in'})
payload = bytes(values, 'ascii')
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(
urllib.request.HTTPRedirectHandler(),
urllib.request.HTTPHandler(debuglevel=0),
urllib.request.HTTPSHandler(debuglevel=0),
urllib.request.HTTPCookieProcessor(cj))
opener.open(get_url) #First call to capture the JSESSIONID
resp = opener.open(post_url, payload)
resp_html = resp.read()
resp_headers = resp.info()
Any other requests using the opener you created will re-use that cookie and you should be able to freely navigate the site.