django rest framework how to close Self describing APIs browsable - django

Like the image, I want to close The browsable API that REST framework provides.
Click to visit directly the JSON data.

In your settings.py file add following code in the section of REST_FRAMEWORK settings
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
),
If you use BrowsableAPIRendereryou will see browsable API interface. JSONRenderer will show JSON data.

Related

Add API key to a header in a DRF browsable API page

I am enabling token/api-key authentication on my API. But once I enable it, I can no longer use the browsable API page of the DRF. I know I can disable the authentication while developing, but this is a question of curiosity: Can I add an api-key to the header of each request sent to the browsable API page? Can I do that by tweaking the Browser settings? Or is it possible to tweak the Browsable API page itself and hardcode the api-key into it?
The better way to handle the situation is to add the SessionAuthentication to the DEFAULT_AUTHENTICATION_CLASSES section in your settings
# settings.py
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.TokenAuthentication",
"rest_framework.authentication.SessionAuthentication",
],
}
More precisely,
# settings.py
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.TokenAuthentication",
],
}
if DEBUG:
REST_FRAMEWORK["DEFAULT_AUTHENTICATION_CLASSES"].append(
"rest_framework.authentication.SessionAuthentication"
)
By doing this, you can either use your APIKey or session key to authenticate the requests.

Django Swagger Rest API, tryit now function when api is on different server to ui

I am trying to document our Django Rest API using Django Swagger Rest API where our API is on different server to UI
Trying to change the TryIt now URL for the curl request as the API is on a different server to the UI
I have tried setting url in get_swagger_view, but this appends ui url before this url
I have tried changing base_path in SWAGGER settings but nothing works
Assuming that you tried absolute url and it didn't work, another way to do that is customize the generator instead of using get_swagger_view function. You can change whatever you need, for instance:
from rest_framework import response, schemas
from rest_framework.decorators import api_view, renderer_classes
from rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer
class CustomRenderer(OpenAPIRenderer):
def get_customizations(self):
data = super().get_customizations()
data['host'] = 'yourdomain.com/path'
return data
#api_view()
#renderer_classes([SwaggerUIRenderer, CustomRenderer])
def swagger_view(request):
generator = schemas.SchemaGenerator(title='Your title')
return response.Response(generator.get_schema(request=request))
Don't forget to configure this function in your urls.py:
urlpatterns = [
url(r'docs^$', swagger_view)
]

Authentication issues with django-webpack-loader with vuejs and django restframework and restauth

I created a frontend with vue.js using vue cli and webpack and the backend using django restframework where I am also implementing social authentication for google using restauth. Before I used the django webpack, the login and logout would work fine and as expected. (I should mention that I was using tokenauthentication) in my settings.py, file I had both the sessionauthentication as well as tokenauthentication enabled in the restframework authentication possibilities. The two settings being enabled never caused any trouble. However, after using the django webpack loader to render the frontend vue files using django templates, I would continuously get an error that said my csrf token was not present. The login would work fine in this case if I removed the sessionauthentication option out of the settings.py file however.
Does anyone know why this is happening?
https://medium.com/#rodrigosmaniotto/integrating-django-and-vuejs-with-vue-cli-3-and-webpack-loader-145c3b98501a
I used the above blog to implement the webpack loader functionality
I removed the 'rest_framework.authentication.SessionAuthentication', line from my settings.py after using the django-webpack-loader and the issue was resolved
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authtoken',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
)
}
I basically changed it like below:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authtoken'
'rest_framework.authentication.BasicAuthentication',
)
}
as you are probably using axios, you need to include these two lines in your main.js
/* configure axios to forward the csrftoken back to Django on POST requests */
axios.defaults.xsrfHeaderName = 'X-CSRFToken';
axios.defaults.xsrfCookieName = 'csrftoken';

JSON Web Token for Django REST won't authenticate to user database

I have a working Django REST API backend. I was previously using session authentication, but would like to move to token based for scaling across multiple servers. I have been researching this for a couple days now and I have not found an answer to my problem. I added the djangorestframework-jwt package to my application but when I try to authenticate is always returns:
{"non_field_errors":["Unable to login with provided credentials."]}
I see in the jwt package where this error is, and can follow the code back through the authentication process. I do not see any errors in the auth process. When I try to create a user with those credentials it says that a user already exists, so I know it is hitting the correct user table. I am not sure why the obtain_jwt_token endpoint will not authenticate my credentials. Below are relevant sections of my django app. Any help would be greatly appreciated. If I am leaving anything out that could help figure this out please let me know and I will upload it. Thanks,
app/settings.py
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 100,}
app/urls.py
urlpatterns = patterns('',
# Api
url(r'^api/', include(router.urls)),
url(r'^api/stats', statsviews.StatsView.as_view()),
url(r'^api/testing', statsviews.TestView.as_view()),
url(r'^api/login', 'rest_framework_jwt.views.obtain_jwt_token'),
url(r'^api/logout', logout, {'next_page': '/api/login'}),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
)
curl command
curl -d "email=test#myemail.com&password=test123" http://webhost.mywebsite.com:8080/api/login/
I have a very similar setup to you. A simple app, utilizing vanilla DRF JWT authentication. The only difference that I can tell is that I have rest_framework_jwt included in my INSTALLED_APPS list:
INSTALLED_APPS = (
...
# Third Party Dependencies
'rest_framework',
'rest_framework_jwt',
'corsheaders',
....
Try adding that and see where it gets you.
I encountered the same problem too,and finally found the way out.
following the quick start guide (http://www.django-rest-framework.org/tutorial/quickstart/) , using python manage.py migrate to create table structure; using python manage.py createsuperuser to create an initial user named admin with a password of "password123"; (attention: the passwords mismatch in guides)
now it should be ok.
$ curl -X POST -d "username=admin&password=password123" http://127.0.0.1:8000/api-token-auth/
{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwidXNlcl9pZCI6MiwiZW1haWwiOiJhZG1pbkA3amdvLmNvbSIsImV4cCI6MTQ3MDY0NjY4Mn0.Dg4KW5pHHJfuaRzjqHTu8kYIzkq8js9}

Django Rest Framework behind HTTP Basic Authentication

If my webservice (powered by Django Rest Framework, v2.3.8) is inside a location protected by Nginx's HTTP Basic Authentication, like so:
location / {
auth_basic "Restricted access";
auth_basic_user_file /path/to/htpasswd;
uwsgi_pass django;
include /etc/uwsgi/config/uwsgi_params;
}
Then, when a user authenticate and tries to access the API, the following response is obtained for all views:
{"detail": "Invalid username/password"}
Does Django Rest Framework pick up the HTTP Authorization header (meant for Nginx) even though the view requires no authentication? If so, how should I go about this?
Any help would be greatly appreciated.
By default, Django Rest Framework has two authentication classes, see here.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication'
)}
You can disable the rest framework authentication if you don't need it.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': ()
}
Or you can remove only BasicAuthentication as it will work in your case.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication'
)}
As noted in another post, you must add a comma next to the authentication class or it can throw a TypeError.
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.authentication.SessionAuthentication', #comma added here
)
Source: https://stackoverflow.com/a/22697034/5687330