【问题标题】:React : LocalStorage with a non-null value alwaysReact:LocalStorage 始终具有非空值
【发布时间】:2020-03-08 20:07:51
【问题描述】:

您好,我正在使用 localStorage 从我的 api 中保存我的 jwt 令牌 但即使我关闭节点服务器等,它也会保存我的令牌。 我需要做一个登录检查

这是我的服务器路由

app.route('/login')
        .post(async (req,res)=>{

            try {
                const response = await usersControllers.signin(req.body);
                const login = response.login;
                console.log(login);
                if(login.id && login.isValid){
                    const payload = {id: login.id};
                    res.json({
                        token: jwt.sign({data:payload}, app.config.jwt.secret,{expiresIn: '60'}),
                        response
                    });
                }else{
                    console.log('entrou here');
                    res.sendStatus(HttpStatus.UNAUTHORIZED);
                } 
            } catch (error) {
                console.log('entrou here');
                console.error(error.message);
                res.sendStatus(HttpStatus.UNAUTHORIZED);
            }
        })

然后在我的前端做出反应

我的登录中有这个:

import React, { Component } from 'react';
import {Form,FormGroup, Label, Input, Button, Alert} from 'reactstrap';
import Header from '../../components/header';

export default class Login extends Component {

    constructor(props) {
        super(props)
        console.log(this.props);
        this.state = {
            message: this.props.location.state?this.props.location.state.message: '',
        };
    }

    signIn = () => {
        const data = {login:this.login,password:this.password};
        const requestInfo = {
            method:'POST',
            body: JSON.stringify({data}),
            headers: new Headers({
                'Content-Type': 'application/json'
            }),
        };
        fetch('http://localhost:9000/login', requestInfo)
        .then(response => {
            if(response.ok){
                return response.json();
            }
            throw new Error("Login Invalido..")
        })
        .then(token => {
            localStorage.setItem('token', token.token);
            this.props.history.push("/users");
            return;
        })
        .catch(e => {
            this.setState({message: e.message})
        });
    }

    render(){
        return(
            <div className="col-md-6">
                <Header title="ReactJS Login"/>
                <hr className="my-3"/>
                {
                    this.state.message !== ''? (
                    <Alert color="danger" className ="text-center"> {this.state.message}</Alert>
                    ) : ''
                }
                <Form>
                    <FormGroup>
                        <Label for="login">Login</Label>
                        <Input type="text" id="login" onChange={e => this.login = e.target.value } placeholder="Informe seu login" />
                    </FormGroup>
                    <FormGroup>
                        <Label for="password">Senha</Label>
                        <Input type="text" id="password" onChange={e => this.password = e.target.value }  placeholder="Informe sua senha"/>
                    </FormGroup>
                    <Button color="primary" onClick={this.signIn}> Entrar </Button>
                </Form>
            </div>
        );
    }
}

在这里我将我的 jwt 设置在 localstorage 中:

.then(token => {
    localStorage.setItem('token', token.token);
    this.props.history.push("/users");
    return;
})

在我的另一个 js 文件中 我对 jwt 的认证

const isAuth = () => {
    console.log(localStorage.getItem('token'));
    if(localStorage.getItem('token') !== null) {
        console.log("entrou aq2");
        return true;
    }
    return false;
};

在 console.log(localStorage.getItem('token'));有价值!==所有时间

即使没有使用我的 api 登录

【问题讨论】:

  • localStorage 中的值永远不会过期。也许您可以考虑改用sessionStorage
  • @dev_junwen 如何创建 sessionStorage?
  • 我在使用重定向将未经身份验证的用户移动到家时遇到问题,但它不起作用。
  • 还有其他“更正确”的选项还是 sessionStorage 是最好的?

标签: node.js reactjs local-storage


【解决方案1】:

使用 JSON.stringify() 保存在本地存储中

.then(token => {
    localStorage.setItem('token', JSON.stringify(token.token));
    this.props.history.push("/users");
    return;
})

并使用 JSON.parse() 从本地存储中获取

const isAuth = () => {
    if(JSON.parse(localStorage.getItem('token')) !== null) {
        console.log("entrou aq2");
        return true;
    }
    return false;
};

【讨论】:

  • 甚至通过重启电脑等关闭服务器。我设置了 60 秒令牌时间
  • @gabriel 关闭标签后你想退出会话吗?
  • 是的,我知道了,但是由于 localsession,它会永远保留令牌,然后它不会进入我的 else
  • 但我不知道有什么更好的方式来存储我的令牌
【解决方案2】:

你的原因

localStorage.getItem('token') !== null

返回true 是因为您使用的是localStoragelocalStorage 的值不会过期,因此您的值将存储在您的localStorage 中,直到您调用

localStorage.removeItem('token')

如果您希望在每次关闭浏览器后删除您的token,请改用sessionStorage。您可以阅读有关使用 SPA 进行身份验证的更多信息here

【讨论】:

  • 你好,谢谢兄弟,我英语不太好,所以我不知道我是否理解得很好,我阅读了所有内容,尤其是这部分:双重提交的cookies和在里面放一个JWT怎么样两全其美的 cookie?
  • 基本上你需要正确理解整个认证过程的概念。然后你可以实现你自己的身份验证方式,这只是一个例子:)
  • 知道了,但是关于双重提交的 cookie 在用户进入网站时创建一个 cookie 并在制作表单并验证时保存此值,这是一个好的选择吗?关于生成(加密强)伪随机值我可以使用 bcrypt 吗?
  • 我将来可能会创建一个身份验证应用程序的示例。如果我这样做了,我会通知您,以便您了解我是如何实现身份验证流程的。
  • 感谢 broooooo 我设法让我的前端在我的 api 中到达 r 我只是难以验证我的令牌我的前端正确发送我的令牌
猜你喜欢
  • 2020-09-24
  • 1970-01-01
  • 2012-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-07
相关资源
最近更新 更多