如何在Angular中使用JWT为列表创建令牌

时间:2018-12-22 21:07:38

标签: angular jwt token

在我的Spring Boot应用程序中,我有表TicketUser,我想显示tickets排序的User列表。

我使用JWT创建用户身份验证,并且想要创建带有tickets列表的令牌。

我创建了用于登录,名称,电子邮件等的令牌,就像您在图片上看到的那样。一切正常。但是我还需要为票证列表创建令牌。为此tickets: Ticket[];

jwt-responce.ts

export class JwtResponse {
accessToken: string;
type: string;
username: string;
user_id: number;
name: string;
surname: string;
email: string;
authorities: string[];
tickets: Ticket[];
}
export class Ticket {
ticket_id: number;
place: number;
user_id: number;
flight_id: number;
}

token-storage.service.ts

我在这里遇到方法saveTicketsgetTickets的问题。我不知道如何为tickets: Ticket[];

正确创建此方法
import { Injectable } from '@angular/core';
import {Ticket} from '../ticket';

const TOKEN_KEY = 'AuthToken';
const USERNAME_KEY = 'AuthUsername';
const NAME_KEY = 'AuthName';
const SURNAME_KEY = 'AuthSurname';
const USERID_KEY = 'AuthUserId';
const EMAIL_KEY = 'AuthEmail';
const TICKET_KEY = 'AuthTicket';
const AUTHORITIES_KEY = 'AuthAuthorities';

@Injectable({
providedIn: 'root'
})
export class TokenStorageService {
private roles: Array<string> = [];
private tickets: Array<Ticket> = [];

constructor() {
}

signOut() {
window.sessionStorage.clear();
}

public saveToken(token: string) {
window.sessionStorage.removeItem(TOKEN_KEY);
window.sessionStorage.setItem(TOKEN_KEY, token);
}

public getToken(): string {
return sessionStorage.getItem(TOKEN_KEY);
}

public saveUsername(username: string) {
window.sessionStorage.removeItem(USERNAME_KEY);
window.sessionStorage.setItem(USERNAME_KEY, username);
}

public getUsername(): string {
return sessionStorage.getItem(USERNAME_KEY);
}

public saveName(name: string) {
window.sessionStorage.removeItem(NAME_KEY);
window.sessionStorage.setItem(NAME_KEY, name);
}

public getName(): string {
return sessionStorage.getItem(NAME_KEY);
}

public saveSurname(name: string) {
window.sessionStorage.removeItem(SURNAME_KEY);
window.sessionStorage.setItem(SURNAME_KEY, name);
}

public getSurname(): string {
return sessionStorage.getItem(SURNAME_KEY);
}

public saveEmail(email: string) {
window.sessionStorage.removeItem(EMAIL_KEY);
window.sessionStorage.setItem(EMAIL_KEY, email);
}

public getEmail(): string {
return sessionStorage.getItem(EMAIL_KEY);
}

public saveAuthorities(authorities: string[]) {
window.sessionStorage.removeItem(AUTHORITIES_KEY);
window.sessionStorage.setItem(AUTHORITIES_KEY, JSON.stringify(authorities));
}

public getAuthorities(): string[] {
this.roles = [];

if (sessionStorage.getItem(TOKEN_KEY)) {
  JSON.parse(sessionStorage.getItem(AUTHORITIES_KEY)).forEach(authority => {
    this.roles.push(authority.authority);
  });
}

return this.roles;
}

getUser_id(): number {
return Number(sessionStorage.getItem(USERID_KEY));
}

saveUser_id(user_id: number) {
window.sessionStorage.removeItem(USERID_KEY);
window.sessionStorage.setItem(USERID_KEY, String(user_id));
}

/*getTickets(): Ticket[] {
this.tickets = [];
if (sessionStorage.getItem(TOKEN_KEY)) {
  JSON.parse(sessionStorage.getItem(TICKET_KEY)).forEach(tickets => {
    this.tickets.push(tickets.tickets);
  });
  return this.tickets;
  }
  }

saveTickets(tickets: Ticket[]) {
window.sessionStorage.removeItem(TICKET_KEY);
window.sessionStorage.setItem(TICKET_KEY, JSON.stringify(tickets));
}*/
}

login.component.ts

import { Component, OnInit } from '@angular/core';

import { AuthService } from '../auth/auth.service';
import { TokenStorageService } from '../auth/token-storage.service';
import { AuthLoginInfo } from '../auth/login-info';

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
form: any = {};
isLoggedIn = false;
isLoginFailed = false;
errorMessage = '';
roles: string[] = [];
/*  tickets  = new Array(1);*/
 private loginInfo: AuthLoginInfo;

constructor(private authService: AuthService, private tokenStorage:    TokenStorageService) { }

ngOnInit() {
if (this.tokenStorage.getToken()) {
  this.isLoggedIn = true;
  this.roles = this.tokenStorage.getAuthorities();
  this.tickets = this.tokenStorage.getTickets();
}
}

onSubmit() {
console.log(this.form);

this.loginInfo = new AuthLoginInfo(
  this.form.username,
  this.form.password);

this.authService.attemptAuth(this.loginInfo).subscribe(
  data => {
    this.tokenStorage.saveToken(data.accessToken);
    this.tokenStorage.saveUsername(data.username);
    this.tokenStorage.saveName(data.name);
    this.tokenStorage.saveSurname(data.surname);
    this.tokenStorage.saveEmail(data.email);
    this.tokenStorage.saveTickets(data.tickets);
    this.tokenStorage.saveAuthorities(data.authorities);
    this.tokenStorage.saveUser_id(data.user_id);

    this.isLoginFailed = false;
    this.isLoggedIn = true;
  /*  this.tickets = this.tokenStorage.getTickets();*/
    this.roles = this.tokenStorage.getAuthorities();
    this.reloadPage();
  },
  error => {
    console.log(error);
    this.errorMessage = error.error.message;
    this.isLoginFailed = true;
  }
);
}

reloadPage() {
window.location.reload();
}
}

home.component.ts

import { Component, OnInit } from '@angular/core';

import { TokenStorageService } from '../auth/token-storage.service';

@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
info: any;

constructor(private token: TokenStorageService) { }

ngOnInit() {
this.info = {
  token: this.token.getToken(),
  username: this.token.getUsername(),
  name: this.token.getName(),
  surname: this.token.getSurname(),
  email: this.token.getEmail(),
  tickets: this.token.getTickets(),
  authorities: this.token.getAuthorities(),
 };
 }

logout() {
this.token.signOut();
window.location.reload();
}
} 

这是我的html类,用于在图片上显示数据:

<div *ngIf="info.token; else loggedOut">
<h5 class="text-primary">Twoje dane</h5>
<p>
<strong>Login:</strong> {{info.username}}<br/>
<strong>Name:</strong> {{info.name}}<br />
<strong>Surname:</strong> {{info.surname}}<br />
<strong>Email:</strong> {{info.email}}<br />
<strong>Role:</strong> {{info.authorities}}<br />
<strong>
<label>List of tickets: </label>
<div *ngFor="let tickets of info.tickets">
  <label>Place: </label> {{ tickets.place }}
</div>
</strong>

enter image description here

1 个答案:

答案 0 :(得分:1)

您的saveTickets示例(注释一个)似乎有点工程化。为什么不以相同的方式存储和还原:

saveTickets(tickets: Ticket[]) {
  sessionStorage.removeItem(TICKET_KEY);      
  sessionStorage.setItem(TICKET_KEY, JSON.stringify(tickets));
}

getTickets(tickets: Ticket[]) {
  try {
    return JSON.parse(sessionStorage.getItem(TICKET_KEY));
  } catch (e) {
    // no or invalid data. Just return empty.
    return [];
}