pythonpython-requestsopenfire

create new users in openfire via user service plugin using python requests


I am trying to write a python program which would add a new user to openfire server . I have enabled user service requests and http basic auth . I am getting Response 401 . This is my code

import requests
from requests.auth import HTTPDigestAuth
def add_controller(name,password):
    xml = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<user>
    <username>""" + name + """</username>
    <password>""" + password + """<password>
</user>"""
    headers = {'Content-Type': 'application/xml','Authorization':'Basic YWRtaW46MTIzNDU='}
    r = requests.post(url='http://192.168.200.115:9090/plugins/userService/users', data=xml, headers=headers ,auth=HTTPDigestAuth('admin','admin'))
    print r

add_controller("test@example.com","test")

Solution

  • You should not set two Authorization headers. You can do Basic or Digest authorization, and the auth argument can handle either. Pick one or the other.

    Using basic auth:

    headers = {'Content-Type': 'application/xml'}
    r = requests.post(
        url='http://192.168.200.115:9090/plugins/userService/users',
        data=xml, headers=headers, 
        auth=('admin', '12345'))
    

    or using digest auth:

    headers = {'Content-Type': 'application/xml'}
    r = requests.post(
        url='http://192.168.200.115:9090/plugins/userService/users',
        data=xml, headers=headers, 
        auth=HTTPDigestAuth('admin', '12345'))
    

    See the dedicated Authentication chapter of the documentation.

    The Openfire user service endpoint should work just fine with the basic auth option.

    You can more easily create the XML document using templating, and you should really use the xml.sax.saxutils.escape() function to ensure your data is suitable for inclusion in the document:

    from xml.sax.saxutils import escape
    
    xml = """\
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <user>
        <username>{}</username>
        <password>{}<password>
    </user>""".format(escape(name), escape(password))