Using Django Rest Framework for only certain apps inside Django Application - django

I'm not sure if this is possible since an extensive search gave me nothing. Or I might be searching the wrong terms.
Now I have a few apps inside my Django application as follows:
--AppOne
--AppTwo
--ExtendedAdmin
manage.py
Now, AppOne and AppTwo use Django Rest Framework and its related Token Auth Mechanism. For the extendedAdmin, I'd like to use native Django Auth or even SessionAuth of DRF since I'm trying to add quite an extensive admin panel to the application. I've not been able to find a satisfactory way of customizing Django Rest Framework to work it's auth mechanisms only for certain applications. Is there a way to do this? If not, what should I be doing different?

So far, I know you cannot. Because django rest framework intercepts the url and then performs its own logic of token validation. But there are solutions that you can use to keep both Session and Token Authentication.
I am using this for all my projects -
I keep Session Authentication for all urls that will be accessed for normal browsing
and I use api urls with django rest framework to be prefixed with /api for my api urls
For example -
The Session Based login is at http://<host>/account/login
and TokenBased login is at http://<host>/api/account/login
The easiest way to make prefixed url for django rest framework is by using Routers - http://www.django-rest-framework.org/api-guide/routers/#defaultrouter
Example -
class UserViewSet(ModelViewSet): # just a sample view set
...
router = routers.SimpleRouter()
router.register(r'api/users', UserViewSet)

Related

Is separating django frontend and backend with API viable?

I'm used to Django and already developed website with a whole Django or with Django API + React.
For a side project, I'm thinking about creating a Django project with 2 apps:
Django API 2) Django Front.
I absolutely want to decouple front/back to be able to reuse the API in the future, and I like the view system from Django.
Is my idea making sense?
Edit 1:
To clarify.
App 1: Django API serving JSON.
App 2: Django App using API calls in the controllers to generate the views.
Edit 2:
I did a proof of concept and it works like a charm.
The only drawback is that I have to use Cookies to store the JWT token and maintain the session state, which is not convenient
it is possible, but completely wrong with idea.
How it possible. Wrong version:
Try to remember, how we can create integrate test for our view. We Should create client and send request to Django to your view-url with args kwargs querystring e.t.c.
In response you have already answer. Try to imagine: part with client - is your Django front, requested part - your backend.
The same works not only in test, you can create request to ask something on the completely other server.
Redis/MemCashed e.t.c. (pattern sender/receiver) Wrong version:
The Front Django speaks with Backend through Third part application. It can be faster.
"Pythonic" version. Right in your case:
You can create Backend Django part like a library with views as interfaces.
Frontend Django part is completely standalone, it import an use interfaces from library, which is your "BackEnd Module".
If you want - you can use "BackEnd Module" everywhere as import, or you can start it as server and ask info per requests.
Completely independent in this case means, you can install "BackEnd Module" without "FrontEnd Module". "FrontEnd Module" can be installed standalone too and it should take from settings, which interfaces should be used as data-source.
I hope, i am right understand your question.
You could definitely separate front and back, remember, django just creates endpoints and consumes them with its own views, you can even use both.
Here is the documentation for django views: https://docs.djangoproject.com/en/4.0/#the-view-layer
You can use a librarie like React as frontend and connect to your api(django app) and use both.

Using Django admin application AND disabling session middleware?

I am building a django server for an API that relies on JWT (or Token based - https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication) authentication for our users.
I don't need session based authentication for any purpose. It creates an unnecessary query on each request, and also authenticates users when I don't want to authenticate them (I want browsers to only authenticate when it includes an Authentication header in the request, and stay AnnonymousUser otherwise. This is because it creates issues in some of my middlewares where I verify if I am dealing with a guest or a authenticated user).
However, the issue comes when I try to use the admin application as well (I can't imagine building this app without the use of the django admin page). When I remove the session-related middlewares:(django.contrib.sessions.middleware.SessionMiddleware, django.contrib.auth.middleware.AuthenticationMiddleware and django.contrib.messages.middleware.MessageMiddleware) from my settings file, I get the following error when I do a runserver:
ERRORS:
?: (admin.E408) 'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application.
?: (admin.E409) 'django.contrib.messages.middleware.MessageMiddleware' must be in MIDDLEWARE in order to use the admin application.
?: (admin.E410) 'django.contrib.sessions.middleware.SessionMiddleware' must be in MIDDLEWARE in order to use the admin application.
Can someone think of a workaround where I can disable sessions in Django, while also being able to use the admin panel? One solution I thought of is to hack up adding the authorization header to each admin page request, but 1) I have no idea how to proceed with this idea and 2) (more importantly), I cannot do a runserver while disabling the session middlewares.

Authenticate VueJS app to Django DRF back end using sessions

Good afternoon,
I am writing an app structured with two docker containers. Docker1 is the front end VueJS app, Docker2 is the backend Django DRF API. I would like to manage access using Sessions (NOT JWT's).
I am having trouble finding resources to help me get started on this approach. Does anyone have any good resources on how to interact with authenticating and managing Django sessions over DRF? Most of the examples use a DJango template form to do initial authentication which is not an option in this case.
EDIT: To be more specific, I intend to make the ajax calls via axios and expect to post to the built-in auth views. My question is around how to handle the csrf_token items.
Thanks for your help.
BCBB

Authenticating Access to Django Rest Framework using custom authentication from a Django App

Ive implemented a custom auth system in one(only) Django app on my project
Now I want to open my site up to Api access, is there a way to only let users from the Django app access this api. As I don't want to repeat myself (DRY) so was asking if it was possible to work backwards rather than to overwrite the Django rest Authentication with very similar code
DRF's SessionAuthentication is included in the default DRF settings and is entirely transparent to users who are already familiar with logging in to your site. You can add it to the list of authenticators for DRF:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
# ...
'rest_framework.authentication.SessionAuthentication',
)
}
The session a user establishes when logging in to your site now also authenticates them for DRF's browsable API and any API calls.
More info: https://www.django-rest-framework.org/api-guide/authentication/#sessionauthentication
If you're instead asking how to do something like issue API keys, DRF's TokenAuthentication can do that for you. You'll just need to add a view to your site that allows users to retrieve their generated tokens.
More info: https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication

Check django user outside django

I have one django app and few small Flask webservices.
In Flask apps I need to validate if the client logged in Django app and grab his pk if possible.
It seems to be possible by taking session ID from a cookie and manually looking into session storage, but I am looking for some less low-level solution.
You need to build a REST api to do that. In the api on the django side you would query the user by whatever criteria you provided and return user.is_authenticated() and user.pk. Take a look at django-rest-framework or tastypie. Then on Flask app you just hit the api and you are done.