Token based authtentication
Token-based authentication is a security technique that authenticates the users who attempt to gain access to a server. The service validates the security token and processes the user request.
How Does Token Authentication Work?
Authentication is the process by which an application confirms user identity. Applications have traditionally persisted identity through session cookies, relying on session IDs stored server-side. This forces developers to create session storage that is either unique to each server, or implemented as a totally separate session storage layer.
Token authentication is a more modern approach and it is designed to solve problems that session IDs storage mechanism on server-side can’t. Using tokens in place of session IDs can lower your server load.
Token CRUD
As a developer, you can use tokens for full CRUD operations. Once an Token is generated, the token can be used to authorize individual requests made by your users as they are passed to your application. Your application will validate the token sent along with each request.
An combination of API Key and API Secret forms a token which is then used to authenticate you with your application and can be used to authenticate both RPC and Rest api.
Generate Token
For every user you can generate an api key and api secret which acts as a token. - api-key: User specific api key, used to identify the user. - api-secret: Used to validate the request.
Note:
- Api key cannot be re-generated.
- Only user's with system manager role can generate keys.
Generate api key and api secret
API key and secret can be generated by the following methods:
- RPC /api/method/frappe.core.doctype.user.user?user="user_name"
- Command bench execute frappe.core.doctype.user.user --args ['user_name']
- Web User -> Api Access -> Generate Keys
Authorization
The HTTP Authorization request header contains the credentials to authenticate a user with a server.
Syntax:
Authorization: <type> <token>
type
There are two types of authorization:
- Token
- Basic
If the "Basic" authentication scheme is used, the credentials are constructed like this: 1. The username and the password are combined with a colon (apikey:apisecret). 2. The resulting string is base64 encoded
credentials
Combination of apikey and apisecret.
api_key:api_secret
Token
{
Authorization: `token <api_key>:<api_secret>`
}
Example:
```
import requests
url = "http://frappe.local:8000/api/method/frappe.auth.getloggeduser"
headers = {
'Authorization': "token
Basic
{
Authorization: Basic base34encode(<api_key>:<api_secret>)
}
Example:
```
import requests
import base64
url = "http://frappe.local:8000/api/method/frappe.auth.getloggeduser"
headers = {
'Authorization': "Basic %s" % base64.b64encode(