Authentication¶
RPC4Django can be used with authenticated HTTP(s) requests and Django’s auth framework.
Where security is a concern, authentication should only be used where SSL or TLS are enabled.
Setup¶
Firstly, the webserver should be configured to use basic HTTP authentication or some sort of single sign on (SSO) solution.
In settings.py, the following changes need to be made:
MIDDLEWARE_CLASSES = (
# ...
# Must be enabled for RPC4Django authenticated method calls
'django.contrib.auth.middleware.AuthenticationMiddleware',
# Required for RPC4Django authenticated method calls
'django.contrib.auth.middleware.RemoteUserMiddleware',
)
# Required for RPC4Django authenticated method calls
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.RemoteUserBackend',
)
Usage¶
To protect a method, it needs to be defined with the @rpcmethod
decorator and the permission
or login_required
parameters.
from rpc4django import rpcmethod
@rpcmethod(name='rpc4django.secret', signature=['string'], permission='auth.add_group')
def secret():
return "Successfully called a protected method"
@rpcmethod(name='rpc4django.restricted', signature=['string'], login_required=True)
def restricted():
return "Successfully called a method for logged in users only"
To call an authenticated method from the Python command prompt, use the following:
from xmlrpclib import ServerProxy
s = ServerProxy('https://username:password@example.com')
s.rpc4django.secret()
Out of the Box Authentication¶
By setting RPC4DJANGO_RESTRICT_OOTB_AUTH
to False
,
system.login
and
system.logout
methods will be enabled. These rely on Django’s SessionMiddleware which requires
a cookie-aware transport.
from xmlrpclib import ServerProxy
from rpc4django.utils import CookieTransport
s = ServerProxy('https://example.com', transport=CookieTransport())
s.rpc4django.secret() # 403 Forbidden
if s.system.login(username, password):
s.rpc4django.secret() # Success!
s.system.logout()