简体   繁体   中英

Python script to get Session Ticket

I have a service, that exposes API for logging in. In my browser if I do

<host>:<port>/myservice/api/login?u=admin&pw=admin

The above url, returns a ticket, that I can pass along for my successive requests.

More details about the same, here.

Below is my python script.

import urllib

url = 'http://<host>:<port>/myservice/api/login?u=admin&pw=admin'
print 'Retrieving', url
uh = urllib.urlopen(url)
data = uh.read()
print 'Retrieved',len(data),'characters'
print data

When I run this I get

IOError: ('http error', 401, 'Authorization Required', <httplib.HTTPMessage instance at 0x<somenumber>>)

Now, I am not sure what am I supposed to do. So I went to my browser, and opened the developer's console.

Apparently, the url has moved to something else. I see two requests.

first one hits the url that I am hitting. Response Header has a Location:Parameter.

The second request hits the url that is returned as Location parameter. the Authorization header has 'Negotiation

It also has a setcookie in the response header.

Now, I am not sure what exactly to do with this information, but if someone can help. Thanks

I believe you problem is having the wrong URL for the login service

If I change you code to instead be:

import urllib, json

url = 'http://localhost:8080/alfresco/service/api/login?u=admin&pw=admin&format=json'
print "Retrieving %s" % url
uh = urllib.urlopen(url)
data = uh.read()
print "Retrieved %d characters" %  len(data)
print "Data is %s" % data

ticket = json.loads(data)["data"]["ticket"]
print "Ticket is %s" % ticket

Then against a freshly installed Alfresco 4.2 server, I get back a login Ticket for the admin user.

Note the use of the json format of the login API - much easier to parse from JSON, and of the correct path to the login api - /alfresco/service/api/login

try this two small changes may be it will help:

1) use urllib.urlencode while passing parameters to request url

import urllib
params = urllib.urlencode({'u': 'admin', 'pw': 'admin'})
uh = urllib.urlopen("http://<host>:<port>/myservice/api/login?%s" % params')

2) Stimulate a web browser while making a request using urllib2

import urllib2
req = urllib2.Request('http://<host>:<port>/myservice/api/login?u=admin&pw=admin', headers={ 'User-Agent': 'Mozilla/5.0' })
uh = urllib2.urlopen(req)

401 is unauthorized error! it means you are not authorized to access API. Did you already signup for API keys and access tokens?

Check detailed description of 401 Error:

http://techproblems.org/http-error-401/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM