Perform the following steps to perform user authentication through RPC:
- Add the jsonrpc_authenticate.py file. You can place this file anywhere you want because the RPC program will work independently.
- Add the following code to the file:
import json
import random
import requests
server_url = 'http://localhost:8069'
db_name = 'test-12'
username = 'admin'
password = 'admin'
json_endpoint = "%s/jsonrpc" % server_url
headers = {"Content-Type": "application/json"}
def get_json_payload(service, method, *args):
return json.dumps({
"jsonrpc": "2.0",
"method": 'call',
"params": {
"service": service,
"method": method,
"args": args
},
"id": random.randint(0, 100000000),
})
payload = get_json_payload("common", "login", db_name, username, password)
response = requests.post(json_endpoint, data=payload, headers=headers)
user_id = response.json()['result']
if user_id:
print("Success: User id is", user_id)
else:
print("Failed: wrong credentials")
- Run the Python script from the Terminal with the following command:
python3 jsonrpc_authenticate.py
When you run the preceding program and you have passed a valid login name and password, the program will print a success message with id of the user, as follows: