I am developing a Hostel Management system using React and Django. The React runs on
localhost:3000
while the django-rest-api runs on
localhost:8000
.
Currently, upon login in
localhost:8000/api/login
, I display user data in JSON format on
localhost:8000/api/user
.
While upon login from frontend
localhost:3000
, The server displays that a user has logged in by returning status 200 and the
last_login
attribute on the
sqlite3
database gets updated too. But as I redirect the user too
localhost:3000/api/student-view
, I get a 403 forbidden error.
I validate user in
views.py
class UserLogin(APIView):
permission_classes = (permissions.AllowAny,)
authentication_classes = (SessionAuthentication,)
def post(self, request):
data = request.data
assert validate_username(data)
assert validate_password(data)
serializer = LoginSerializer(data=data) ## Validates user data
if serializer.is_valid(raise_exception=True):
user = serializer.check_user(data)
login(request, user)
return Response(serializer.data, status=status.HTTP_200_OK)
class UserView(APIView):
permission_classes = (permissions.IsAuthenticated,)
authentication_classes = (SessionAuthentication,)
def get(self, request):
serializer = StudentViewSerializer(request.user)
return Response({"user": serializer.data}, status=status.HTTP_200_OK)
I POST
the data to the server from Login.js
. Server logs that the user is valid here.
function submitLogin(e) {
e.preventDefault();
client.post(
"/api/login",
username: username,
password: password
}, {withCredentials: true}
).then(response => {
if (response.status === 200) {
navigate("/student-view", {replace: true});
return response;
}).catch(err => {
console.log("Error", err)
Finally StudentView.js
should make a GET
from localhost:3000/api/user
, which gives a 403.
const client = axios.create({
baseURL: "http://127.0.0.1:8000"
function StudentView() {
const [posts, setPosts] = useState([]);
useEffect(() => {
client
.get("/api/user")
.then((result) => {
console.log(result.data);
setPosts(result.data);
.catch((error) => console.log(error));
}, []);
return (
{posts.map((data) => {
return (
<div key={data.id}>
<h4>{data.title}</h4>
<p>{data.body}</p>
Also in my settings.py
,
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
"http://127.0.0.1",
"http://0.0.0.0",
On the server side I get
Forbidden: /api/user
[19/Mar/2024 13:03:54] "GET /api/user HTTP/1.1" 403 58
While on the frontend I get
AxiosError {message: 'Request failed with status code 403', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
My first suggestion would be to check that your get("/api/user")
call is sending the correct session id cookie.
Verify what you’re getting back from the login for a session id, and ensure that this get is returning that same value.