使用JWT进行身份验证

时间:2018-08-21 16:57:33

标签: reactjs authentication jwt

我试图在React / Laravel中向我的应用程序添加身份验证系统。为此,我要求理论恢复通行证上的令牌。问题是它返回了一个未定义的令牌...但是,当我查看浏览器的控制台时,在预览中看到了该令牌... 有人可以指导我解决这个问题吗?

这是我的Auth服务的代码

import decode from 'jwt-decode';

export default class AuthService {
// Initializing important variables
constructor(domain) {
    this.domain = domain || 'http://127.0.0.1:8000' // API server 
    domain
    this.fetch = this.fetch.bind(this) // React binding stuff
    this.login = this.login.bind(this)
    this.getProfile = this.getProfile.bind(this)
}

login(username, password) {
    // Get a token from api server using the fetch api
    return this.fetch(`${this.domain}/oauth/token`, {
        method: 'POST',
        body: JSON.stringify({
            username,
            password,
            grant_type: "password",
            client_id:"2",
            client_secret : "Wu07Aqy9pU5pLO9ooTsqYDBpOdzGwrhvw5DahcEo"
        })
    }).then(res => {
        this.setToken(res.token) // Setting the token in localStorage
        return Promise.resolve(res);

    })
}

loggedIn() {
    // Checks if there is a saved token and it's still valid
    const token = this.getToken() // GEtting token from localstorage
    return !!token && !this.isTokenExpired(token) // handwaiving here
}

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

setToken(token) {
    // Saves user token to localStorage
    localStorage.setItem('access_token', token)
}

getToken() {
    // Retrieves the user token from localStorage
    return localStorage.getItem('access_token')
}

logout() {
    // Clear user token and profile data from localStorage
    localStorage.removeItem('access_token');
}

getProfile() {
    // Using jwt-decode npm package to decode the token
    return decode(this.getToken());
}


fetch(url, options) {
    // performs api calls sending the required authentication headers
    const headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    }

    // Setting Authorization header
    // Authorization: Bearer xxxxxxx.xxxxxxxx.xxxxxx
    if (this.loggedIn()) {
        headers['Authorization'] = 'Bearer ' + this.getToken()
    }

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

_checkStatus(response) {
    // raises an error in case response status is not a success
    if (response.status >= 200 && response.status < 300) { // Success 
status lies between 200 to 300
        return response
    } else {
        var error = new Error(response.statusText)
        error.response = response
        throw error
    }
}
}

我的表单

import React, { Component } from 'react';
import AuthService from './AuthService';
import { Router, Route, Switch, Link } from 'react-router-dom'



class Login extends Component {
constructor(){
    super();
    this.handleChange = this.handleChange.bind(this);
    this.handleFormSubmit = this.handleFormSubmit.bind(this);
    this.Auth = new AuthService();
}

handleFormSubmit(e){
       e.preventDefault();

       this.Auth.login(this.state.username,this.state.password)
           .then(res =>{
              this.props.history.replace('/Localisations');
           })
           .catch(err =>{
               alert(err);
           })
   }

   componentWillMount(){
if(this.Auth.loggedIn())
    this.props.history.replace('/');
}


render() {
    return (
        <div className="center">
            <div className="card">
                <h1>Login</h1>

                <form onSubmit={this.handleFormSubmit}>
                    <input
                        className="form-item"
                        placeholder="Username goes here..."
                        name="username"
                        type="text"
                        onChange={this.handleChange}
                    />
                    <input
                        className="form-item"
                        placeholder="Password goes here..."
                        name="password"
                        type="password"
                        onChange={this.handleChange}
                    />
                    <input
                        className="form-submit"
                        value="Submit"
                        type="submit"
                    />
                </form>

            </div>
        </div>
    );
}

handleChange(e){
    this.setState(
        {
            [e.target.name]: e.target.value
        }
    )
}
}

export default Login;

还有我的Auth

import React, { Component } from 'react';

从“ ./AuthService”导入AuthService;

export default function withAuth(AuthComponent) {
const Auth = new AuthService('http://127.0.0.1:8000');
return class AuthWrapped extends Component {
    constructor() {
        super();
        this.state = {
            user: null
        }
    }
    componentWillMount() {
        if (!Auth.loggedIn()) {
            this.props.history.push('/Localisations')
        }
        else {
            try {
                const profile = Auth.getProfile()
                this.setState({
                    user: profile
                })
            }
            catch(err){
                Auth.logout()
                this.props.history.push('/')
            }
        }
    }

    render() {
        if (this.state.user) {
            return (
                <AuthComponent history={this.props.history} user= . 
 {this.state.user} />
            )
        }
        else {
            return null
        }
    }
};
}

0 个答案:

没有答案