Angular(v5)使用Node / Express在本地存储和路由中存储JWT

时间:2018-04-14 12:52:47

标签: node.js angular express local-storage jwt

我想将jwt存储在本地存储中,其中包含来自node / express的角度,并在前端打开一个配置文件路径。

我的MEAN app结构:

dir: config
dir: models
dir: ngview(angular app)
dir: routes : auth.js , user.js
file: index.js

我的Angular应用程序(NGVIEW / src / app)结构:

dir: components : dashboard, home, login, navbar, profile, register
dir: interfaces : config.ts
dir: services : config.service.ts
file : app.module.ts

后端:routes / user.js

const user = require('../models/schema');
const express = require('express');
const router = express.Router();
const auth = require('./auth');

// Requiring JsonWebToken

const jwt = require('jsonwebtoken');

// login api
router.post('/login', function (req, res) {
  let criteria ={
      username : req.body.username,
      password : req.body.password
  };
  user.findOne(criteria,function(err, result){
      if(err) return res.json(err);
      else if(result){
        let myToken = jwt.sign({ id: user._id }, "secretkey", { expiresIn: 86400 });
        return res.json({ result : result, token : myToken})
    }   
  });
});


router.use('/auth/*', function(req, res, next) {
  let myToken = req.headers['x-access-token'];
  if (!myToken) return res.status(401).send({ auth: false, message: 'No token provided.' });

  jwt.verify(myToken, "secretkey", function(err, decoded) {
    if (err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
    return next()
    // res.status(200).send(decoded);
  });
});

router.use('/auth', auth);

module.exports = router;

后端:routes / auth.js

const user = require('../models/schema');
const express = require('express');
const auth = express.Router();


// profile api
auth.get('/profile', function (req, res) {
    let value = {};
    user.find(value, function(err, results){
      if(err) res.json(err);
      res.json(results);
    });
});

module.exports = auth;

Angular:ngview / src / app / components / login / login.components.ts

import { Component, OnInit } from '@angular/core';
import { ConfigService } from '../../services/config.service';
import { Config } from '../../interfaces/config';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  username: string;
  password: string;

  constructor(private configService: ConfigService,private router: Router) { }

  ngOnInit() {
  }
  config : Config;
  configs : any;


  logedConfig() {
    const newConfiged = {
      username: this.username,
      password: this.password
    };
    this.configService.logConfig(newConfiged)
    // .subscribe(config => this.configs);
    .subscribe(data => {
      if(data){
      this.configService.storeUserData(data);
      this.configs = data
      this.router.navigate(['/dashboard']);
      } else{
      this.router.navigate(['/login']);
      }
    } );
  }

}

Angular:ngview / src / app / services / config.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Config } from '../interfaces/config';
import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'x-access-token': this.authToken
  })
};

@Injectable()
export class ConfigService {
  authToken: any;

  constructor(private http: HttpClient) { }

  configUrl = 'api/users';

  postUrl = 'api/register';

  deleteUrl = 'api/user';

  loginUrl = 'api/login';

  getConfig() {
    // now returns an Observable of Config
    return this.http.get<Config>(this.configUrl);
  }

  /** POST: add a new hero to the database */
  addConfig (config: Config): Observable<Config> {
    return this.http.post<Config>(this.postUrl, config, httpOptions)
  }

  deleteConfig (): Observable<{}> {
    // const url = `${this.deleteUrl}/${id}`; // DELETE api/heroes/42
    return this.http.delete(this.deleteUrl, httpOptions)
  }
  logConfig (config: Config): Observable<Config> {
    return this.http.post<Config>(this.loginUrl, config, httpOptions)
  }
  storeUserData(token) {
    localStorage.setItem('token', token);
    this.authToken = token;
  }
}

0 个答案:

没有答案