在reactjs中使用fetch来检查是“管理员”还是“用户”

问题描述 投票:-1回答:2

我需要验证角色何时使用令牌来授予用户(使用访存API),如果角色==“ admin”或“ user”。如果角色==“ admin”,则重定向到/ accounts,例如,否则,如果它是“用户”,则将身份验证表单隐藏在render中,并在页面上制作一些动画(css / js)(如果可以隐藏其他内容)如果是简单用户而不是管理员。

这是我的代码这是通过良好的管理员身份验证的结果,这里的标记是“结果”:

{
    "success": true,
    "message": "SUCCESS",
    "result": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50IjpbeyJkYXRlQ3JlYXRpb24iOiIyMDE5LTEwLTI0VDEwOjMyOjMwLjczMFoiLCJyZXNldHBhc3N3b3JkdG9rZW4iOm51bGwsInJlc2V0cGFzc3dvcmRleHBpcmVzIjpudWxsLCJyb2xlIjoiYWRtaW4iLCJlbmFibGUiOnRydWUsIl9pZCI6IjVkYjE3Zjg2M2ZhZjNmMTE1NDQ3OWVlNiIsImVtYWlsIjoic2FhcmFhYWFjaGVtbGFsQGdtYWlsLmNvbSIsInBhc3N3b3JkIjoiJDJiJDEwJGxGSUpKQVBXUmVaZ0MvTWpEaGJuSGVjUzdGb3d3QTlUU2pMTlRmVXdRWEpQdlgwTmhDTXd1IiwidGlja2V0cyI6W10sImdhaW5zIjpbXSwiX192IjowLCJub20iOiJBQ0hFTUxBTF8iLCJwcmVub20iOiJNRVJZRU1fIiwidGVsIjoiMDYxOTU2MjcyMSJ9XSwiaWF0IjoxNTcyMDQzOTUyfQ.ZuNdWcWfu-J_dvgCmUH_w8EAx4FIeSMvAqG8ebm1ilc"
}

简单用户的身份验证是相同的,只有令牌会更改我有用于登录的提取API:

constructor (props) {
    super(props);
    this.state = {
      cnx_mail: '',
      cnx_pwd: '',
      items: [],
      token : '',
      errors: {},

      formErrors: {cnx_mail: '', cnx_pwd: ''},
      emailValid: false,
      passwordValid: false,
      formValid: false
    }
     this.handleUserInput = this.handleUserInput.bind(this);
     this.handleSubmit = this.handleSubmit.bind(this);
  }

handleSubmit = (event) => {
    event.preventDefault();
    fetch(`${API}/api/connexion`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',   
          },
        body: JSON.stringify ({
            email: this.state.cnx_mail,
            password: this.state.cnx_pwd,
          })
    })
    .then(res => res.json())
    .then(json => {
        console.log(json);
        localStorage.setItem('toktok', json.result);
        // Redirect here if Admin  this.props.history.push('/accounts');  Else hide the authentication form in render()      

    }); 
  }

render()中的我的身份验证表单>当角色==用户时将其隐藏:

<form className="demoForm" onSubmit={this.handleSubmit} noValidate  encType="application/x-www-form-urlencoded">
                                <div className="alreadysubscribed-input">
                                    <div className={`alreadysubscribed-field group-input ${this.errorClass(this.state.formErrors.cnx_mail)}`}>
                                        <input type="email" required className="form-control fatb-input input-form" name="cnx_mail"
                                            value={this.state.cnx_mail}
                                            id="cnx_mail"
                                            onChange={this.handleUserInput} error={errors.cnx_mail} />
                                            <label className="fatb-label" htmlFor="cnx_mail">Email</label>
                                            <div className="fatb-bar"></div>                                  
                                    </div>

                                    <div className={`alreadysubscribed-field group-input ${this.errorClass(this.state.formErrors.cnx_pwd)}`}>
                                        <input type="password" required className="form-control fatb-input input-form" name="cnx_pwd"
                                            value={this.state.cnx_pwd}
                                            id="cnx_pwd"
                                            onChange={this.handleUserInput} error={errors.cnx_pwd} />
                                            <label className="fatb-label" htmlFor="cnx_pwd">Mot de passe</label>
                                            <div className="fatb-bar"></div>
                                    </div>
                                </div>
                                <FormErrors formErrors={this.state.formErrors} />

                                <div className="btn-cnx">
                                    {/* <span className="mas">Se connecter</span> */}
                                    <button className="fatb-btn bubbly-button btn-anim3 w100p" type="submit"  name="cnx_btn" disabled={!this.state.formValid}>se connecter</button>
                                </div>
                            </form>
javascript reactjs api fetch-api
2个回答
0
投票

似乎您的令牌采用JWT或“ JSON Web令牌”的格式。

首先,请注意:通过这样的API公开JWT是非常危险的。最好让JWT通过安全的,仅HTTP的cookie进行传输。如果不良玩家获得了此JWT令牌,则他们可以代表用户执行任务。

话虽如此,如果您坚持要向浏览器公开用户的令牌,请知道可以对JWT进行解码以公开其有效载荷。您在此处发布的JWT具有此有效负载:

{
  "account": [
    {
      "dateCreation": "2019-10-24T10:32:30.730Z",
      "resetpasswordtoken": null,
      "resetpasswordexpires": null,
      "role": "admin",
      "enable": true,
      "_id": "5db17f863faf3f1154479ee6",
      "email": "[email protected]",
      "password": "$2b$10$lFIJJAPWReZgC/MjDhbnHecS7FowwA9TSjLNTfUwQXJPvX0NhCMwu",
      "tickets": [],
      "gains": [],
      "__v": 0,
      "nom": "ACHEMLAL_",
      "prenom": "MERYEM_",
      "tel": "0619562721"
    }
  ],
  "iat": 1572043952
}

您可以阅读account.role属性来决定在应用程序中要做什么。 See the JWT spec有关如何解析JWT的更多详细信息,或者可能有可用的库为您提供。

同样,我告诫您不要在API中返回JWT。您总是可以公开它的[签名位,使其无法用作身份验证令牌(将其拆分为.字符并返回有效载荷段);那么在客户端,您只需要对字符串进行base64解码即可。也许您的API可以为您完成解码。


0
投票
这里是您检查令牌中的role的方式

// fake the result: var json = { result: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50IjpbeyJkYXRlQ3JlYXRpb24iOiIyMDE5LTEwLTI0VDEwOjMyOjMwLjczMFoiLCJyZXNldHBhc3N3b3JkdG9rZW4iOm51bGwsInJlc2V0cGFzc3dvcmRleHBpcmVzIjpudWxsLCJyb2xlIjoiYWRtaW4iLCJlbmFibGUiOnRydWUsIl9pZCI6IjVkYjE3Zjg2M2ZhZjNmMTE1NDQ3OWVlNiIsImVtYWlsIjoic2FhcmFhYWFjaGVtbGFsQGdtYWlsLmNvbSIsInBhc3N3b3JkIjoiJDJiJDEwJGxGSUpKQVBXUmVaZ0MvTWpEaGJuSGVjUzdGb3d3QTlUU2pMTlRmVXdRWEpQdlgwTmhDTXd1IiwidGlja2V0cyI6W10sImdhaW5zIjpbXSwiX192IjowLCJub20iOiJBQ0hFTUxBTF8iLCJwcmVub20iOiJNRVJZRU1fIiwidGVsIjoiMDYxOTU2MjcyMSJ9XSwiaWF0IjoxNTcyMDQzOTUyfQ.ZuNdWcWfu-J_dvgCmUH_w8EAx4FIeSMvAqG8ebm1ilc" }; // this one line is your answer const isAdmin = JSON.parse(atob(json.result.split('.')[1])).account[0].role === 'admin'; // console.log(isAdmin);
警告

令牌有效载荷如下

{ "account": [ { "dateCreation": "2019-10-24T10:32:30.730Z", "resetpasswordtoken": null, "resetpasswordexpires": null, "role": "admin", "enable": true, "_id": "5db17f863faf3f1154479ee6", "email": "[email protected]", "password": "$2b$10$lFIJJAPWReZgC/MjDhbnHecS7FowwA9TSjLNTfUwQXJPvX0NhCMwu", "tickets": [], "gains": [], "__v": 0, "nom": "ACHEMLAL_", "prenom": "MERYEM_", "tel": "0619562721" } ], "iat": 1572043952 }

里面有很多个人信息!!!即个人信息的一个字段太多了
© www.soinside.com 2019 - 2024. All rights reserved.