CSRF_FAILURE_VIEW with Django rest framework does not work - django-rest-framework

Using the TokenAuthentication from DRF to authenticate the web frontend. We have a situation where some times the CSRF cookie becomes invalid due to using different URLs to access the same website. Of cause the user needs to clear the cookies before they can log in again (all expected behaviour).
Would like to delete the cookies with Django by setting the CSRF_FAILURE_VIEW value within the django setting and have a custom view that calls request.session.delete()
But...
DRF overrides the function _reject for the Django class CsrfViewMiddleware which means the setting CSRF_FAILURE_VIEW is never accessed.
class CSRFCheck(CsrfViewMiddleware):
def _reject(self, request, reason):
# Return the failure reason instead of an HttpResponse
return reason
Any ideas as to how this can be addressed?

Related

How to do custom checking before the REST API called in Spring?

I have a problem where the user still can call the API after logout the application by using POSTMAN. There is no problem with the browser side after logged out since I have removed the access token and clear the cookies. But the user still can call the API and get the results using POSTMAN, which means the back-end doesn't invalidate the OAuth token. This may cause security issues if anyone stole the access code.
I have think to apply validation before the API called. I will add a column in the database table which its' value is either login or logout to indicate the current user status. Then, I will fetch this value from database for every API called to do validation. If the value is logout, then the API will return some error message. Is it possible to do by using the spring security?

Is it possible to protect Get Requests in Spring Boot MVC with Recaptcha (inside the Spring Boot Application)

Let's say when you send a request to this url: ...?query=something&filter=another_thing, I am returning a web page with model attribute let's say model.addAttribute('result', resultList) then just for loop the result and print the values. (Template resolver could be jsp or thymeleaf, but there is no option to load resultList without model fashion - I mean there is no ajax request - )
What I want to do:
before loading the result (or loading the page), I just want to load google recaptcha.js first and
recaptcha will return a token,
then I will send token to the backend via ajax request.
After all if request is not bot, I will print the resultList
Is this requirement possible to implement inside the Spring boot application itself?
NOTE: I could not find anyway to do this. I just though that I could intercept the original get url then redirect to the another page, and this page will load recaptcha and send the token to my backend. If it is not bot then redirect to the original get url. However I do not know how to preserve original request
You're framing it slightly wrong, which may make all the difference.
When making a request, you want to make sure that request is authorized, before you handle
it.
That is where a recaptcha comes in.
To prevent unauthorized access, look into spring-security and recaptcha for that.
Once sufficient authentication has been achieved, your request will then enter your controller, and you can serve the page.
(of course, you could look into it doing it dynamically, but that will be a bit harder)

Add multiple authentication mechanism for different api groups springboot

We have an existing spring-boot application that supports basic Authentication with spring-security. this application uses spring templating so it accepts form data as input and saves sessions by doing authentication.
the login page is at /login after successful login it redirects to the home page of the website.
in the same spring boot service, we want to start supporting JSON based API which would be used by the Mobile app.
we were thinking of adding login API at /api/login which will be served for mobile devices.
is there a way where we can say
for /login use default authentication class and for /api/login use some other custom class which will read JSON data and will do Authentication.
we also want to use different page for unAuthorized access. as existing one renders custom HTML page. but with API we want to send JSON response with HTTP code.
Not a Java person, but generally speaking this can be done by creating a different controller that would handle the /api/login route.
Here's snippet below that might help :
[Source : https://spring.io/guides/gs/spring-boot/]
package com.example.springboot;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
#RestController
public class HelloController {
#RequestMapping("/api/login")
public String LoginAPI() {
// handle your authentication logic here.
}
}
I would strongly recommend against using the session based authentication. It's simply not designed for modern applications. If the option is open, you can take a upgrade to token based authentication (jwt.io), that would make your life much much easier.
If you must implement the session based authentication for mobile app as well. here's what you need to do
create the session on server
set the session key as a part of cookies in the response header
store the cookies in your app.
Include the cookies in request header in subsequent API calls from mobile app.
Again, not a Java person. Just hoping to help.

using authenticated session/user for REST API in eXist-db

I have a public website running from an eXist app. I am now developing an interface for logged in users to edit certain documents through HTML forms and AJAX. I've set up a module in eXist to receive AJAX POST requests through the eXist REST interface (ie. http://www.example.com/exist/rest/db/myapp/api/myxquery.xql). However this module does not seem to be aware of the fact that the user is already logged in!
How do I get the REST module to use the session/authentication of the logged in user?
Am I required to store the user/password in the browser to pass with each REST API request?
If this is not the preferred model for passing data from the browser under user/password, what is eXist's recommended solution?
Many thanks in advance.
(A variation on this question was asked two years ago but received no solutions.)
In order to use the REST-API from existdb you can only authenticate each request using HTTP Basic Authentication. Also mentioned in the question you referenced.
If you decide to handle AJAX request in your app's controller.xql you will need to:
Add routes for your AJAX requests to the controller
Make sure you call login:set-user for the user session to be picked up
Make sure the AJAX request sends the cookie:
For instance, the fetch function will send the authorisation cookie
only if send-authorization is true.
Look at the output-method and serialization settings, since you will likely want to respond in JSON-format. useful blog post about this

Contentful wehook returns 403 when integrated with django rest

I setup a contentful account for downloading videos and its returning 403 when i tried to add a webhhok to an api in my django rest project. I am new to both django rest and contentful.
http://my_server_id/testhook
I setup the hook and added my api url. So it called my api when the event triggered. But all time in django rest it shows forbidden.What extra measures should i choose when integrating webhook with django rest?
Your problem probably because of csrf token, you should pass it in a header with a POST request.
X-CSRFToken: value.
docs about csrf
Like #Linovia said in comment, csrf_exempt already exempted in a view, but because of session there is still an explicit check.
Here is a nice answer about this problem:
Django Rest Framework remove csrf
In a nutshell you could inherit from SessionAuthentication class and override enforce_csrf.
from rest_framework.authentication import SessionAuthentication
class CsrfExemptSessionAuthentication(SessionAuthentication):
def enforce_csrf(self, request):
return # To not perform the csrf check previously happening
Set it in a view or in a basic Django REST config:
authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)

Resources