首页 > 解决方案 > 如何在 React 中访问 Django 会话

问题描述

如果我使用 Django REST 框架进行会话身份验证

https://www.django-rest-framework.org/api-guide/authentication/

在前端 React,我想知道如何确定我的会话是否在 React 中的 Django 中处于活动状态?我假设会话是通过在客户端浏览器中设置一个 cookie 来实现的,因此每次从客户端发送请求时,它都会在标头中包含这个 cookie,Django 会自动从中读取。如果是这种情况,访问此 cookie 的最佳方式是什么?或者更确切地说,检查用户是否仍然直接通过身份验证的理想方法是什么?现在我可以向端点发送请求,如果我没有通过身份验证,它将抛出 403 错误,但在我看来,这不是在前端检查登录状态的优雅方法。

标签: djangoreactjssessiondjango-rest-frameworksession-cookies

解决方案


# You can check in the constructor of your component whether the token is set or not. If not, redirect the page to login page. And remove the token in the logout component.

# For example

admin.js

import React, { Component } from 'react'
import { Link, Redirect } from 'react-router-dom';

export default class Admin extends Component {
    constructor(props) {
        super(props)
        const token = localStorage.getItem("token")

        let loggedIn = true

        if (token == null) {
            loggedIn = false
        }

        this.state = {
            loggedIn
        }
    }

    render() {
        if(this.state.loggedIn === false){
            return <Redirect to="/" />
        }
        return (
            <div>
                <h1>This is an Admin Page. Only Auth people can see this.</h1>
                <Link to="/logout">Logout</Link>
            </div>
        )
    }
}


logout.js

import React, { Component } from 'react'
import { Link } from 'react-router-dom';

export default class Logout extends Component {
    constructor(props){
        super(props)
        localStorage.removeItem("token")
    }
    render() {
        return (
            <div>
                <h1>You have been logged out!!!</h1>
                <Link to="/">Login again</Link>
            </div>
        )
    }
}

推荐阅读