简体   繁体   English

如何使用 reactjs 中的 jwt-decode 库解码 JWT 令牌

[英]How to decode JWT token by using jwt-decode library in reactjs

I'm new to react, i wanted to add JWT authentication to my SPA.我是新手,我想将 JWT 身份验证添加到我的 SPA 中。 my Objective is i'm getting token in localstorage of Application but unable to decode the token.我的目标是我在应用程序的本地存储中获取令牌但无法解码令牌。 I couldn't able to figure it out where i'm going wrong.我无法弄清楚我哪里出错了。 Can anyone assist me to get decoded.谁能帮我解码。 Here is a sample token generated by my API - m5iZiI6MTU4ODQwNjQ5MywiZXhwIjoxNTg4NTc5MjkzLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjQ1MDkyLyIsImF1ZCI6Imh0dHA6Ly9sb2NhbGhvc3Q6NDUwOTIvIn0.MjmDKCoQoEOLKtoL_iUAAqE7hnE2xmUdnCB6JdaGX3w . Here is a sample token generated by my API - m5iZiI6MTU4ODQwNjQ5MywiZXhwIjoxNTg4NTc5MjkzLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjQ1MDkyLyIsImF1ZCI6Imh0dHA6Ly9sb2NhbGhvc3Q6NDUwOTIvIn0.MjmDKCoQoEOLKtoL_iUAAqE7hnE2xmUdnCB6JdaGX3w .

Here is AuthService code:这是 AuthService 代码:

import decode from 'jwt-decode';
export default class AuthService {
    constructor(domain) {
        this.domain = domain || '/api/Login/auth'
        this.fetch = this.fetch.bind(this) // React binding stuff
        this.login = this.login.bind(this)
        this.getProfile = this.getProfile.bind(this)
    }

    login = (email, password) => {
        return this.fetch(`${this.domain}`, {
            method: 'POST',
            body: JSON.stringify({
                email,
                password
            })
        }).then(res => {
            this.setToken(res.token)
            return Promise.resolve(res);
        })
    }

    loggedIn () {
        const token = this.getToken()
        return !!token && !this.isTokenExpired(token)
    }

    isTokenExpired (token) {
        try {
            const decoded = decode(token);
            if (decoded.exp < Date.now() / 1000) {
                return true;
            }
            else
                return false;
        }
        catch (err) {
            return false;
        }
    }

    setToken (idToken) {
        localStorage.setItem('id_token', idToken)
        console.log("token values", idToken)
    }

    getToken () {
        return localStorage.getItem('id_token')
    }

    logout () {
        localStorage.removeItem('id_token');
    }

    getProfile () {
        return decode(this.getToken());
    }


    fetch (url, options) {
        const headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }
        if (this.loggedIn()) {
            headers['Authorization'] = 'Bearer ' + this.getToken()
        }

        return fetch(url, {
            headers,
            ...options
        })
            .then(this._checkStatus)
            .then(response => response.json())
    }

    _checkStatus (response) {

        if (response.status >= 200 && response.status < 300) {
            return response
        } else {
            var error = new Error(response.statusText)
            error.response = response
            throw error
        }
    }
}

Login.js Code: Login.js 代码:

import React from 'react';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import Container from '@material-ui/core/Container';
import AuthService from '../../service/AuthService';

class LoginComponent extends React.Component {

    constructor(props){
        super(props);
        this.state = {
            username: '',
            password: '',
            message: '',
        }
        this.login = this.login.bind(this);
this.Auth = new AuthService();
    }

   componentWillMount () {
    if (this.Auth.loggedIn())
      this.props.history.replace('/');
  }
    login = (e) => {
        e.preventDefault();
       this.Auth.login(this.state.email, this.state.password).then(res => {
            if(res.status === 200){
                localStorage.setItem("userInfo", JSON.stringify(res));
                this.props.history.push('/');
            }else {
                this.setState({message: res.data.message});
            }
        });
    };

    onChange = (e) =>
        this.setState({ [e.target.name]: e.target.value });

    render() {
        return(
            <React.Fragment>
                <AppBar position="static">
                    <Toolbar>
                        <Typography variant="h6">
                            React User Application
                        </Typography>
                    </Toolbar>
                </AppBar>
                <Container maxWidth="sm">
                    <Typography variant="h4" style={styles.center}>Login</Typography>
                    <form>
                        <Typography variant="h4" style={styles.notification}>{this.state.message}</Typography>
                        <TextField type="text" label="USERNAME" fullWidth margin="normal" name="username" value={this.state.username} onChange={this.onChange}/>

                        <TextField type="password" label="PASSWORD" fullWidth margin="normal" name="password" value={this.state.password} onChange={this.onChange}/>

                        <Button variant="contained" color="secondary" onClick={this.login}>Login</Button>
                    </form>
                </Container>
            </React.Fragment>
        )
    }

}

const styles= {
    center :{
        display: 'flex',
        justifyContent: 'center'

    },
    notification: {
        display: 'flex',
        justifyContent: 'center',
        color: '#dc3545'
    }
}

export default LoginComponent;

Can anyone help me or suggest me any appropriate link?任何人都可以帮助我或建议我任何适当的链接吗?

Your sample token looks like a valid token, and it should be successfully decoded.您的示例令牌看起来像一个有效的令牌,它应该被成功解码。

So please be sure that you are accessing only these fields, there is no role or user_id field.所以请确保您只访问这些字段,没有roleuser_id字段。 If you add those fields to the token when generating, they will display.如果在生成时将这些字段添加到令牌中,它们将显示出来。

It may be the problem of Parsing just try this可能是解析的问题,试试这个

getToken () {
    return JSON.parse(localStorage.getItem('id_token'));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM