Appearance
Django Rest Framework - Security
Permissions
- can use built in permissions by updating settings'
DEFAULT_PERMISSION_CLASSES - has built in auth URL
path("api-auth/", include("rest_framework.urls")), - can assign permissions to specific views using
permission_classes
Custom Permissions
- custom permissions should inherit from
BasePermissionclass- is strongly advised to always set both
has_permissionandhas_object_permissionmethods explicitly because each defaults toTrue has_permissionworks on list views while detail views execute both
- is strongly advised to always set both
Authentication
Four options: basic, session, token and default
- Basic
- every request verifies username and password
- inefficient
- every request verifies username and password
- Session
- uses session ids to verify authentication
- a stateful approach because session ids must be maintained on both server and client
- is generally not advised to use session based auth for any API that will have more than one front end
- sessions cannot cross domains only the domain where the initial login occurred
- Token
- most popular option currently
- stateless auth
- once credentials are verified a token is generated and then returned and stored by the client
- the server does not keep a record of the user, only whether a token is valid or not
- best practice is to store tokens in a cookie with the
httpOnlyandSecurecookie flags - tokens can cross domains and represent a user on a website and mobile app
- tokens can grow in size and become a performance issue
- JSON Web Tokens (JWTs)
- a newer form of token containing cryptographically signed JSON data
- originally designed for use in OAuth
- third party packages
django-allauth- comes with user registration endpoints
- allows for social auth via google, etc.
- can be updated to handle registration confirmation emails
dj-rest-auth
JWT Tokens
- login
- get an
access_tokenreturned - get a
refresh_tokenreturned inHeaders
- get an
- for authenticated API requests like the
/me/and/logout/endpoint theaccess_tokenis passed as anAuthorizationheaderAuthorization: Bearer - the
refresh_tokenis only used to get a newaccess_token- access_token is returned in
Headers
- access_token is returned in
