[英]Problem with authorization in Angular 13 in web-app project
我在 angular 13 版本的項目中遇到授權問題。 在 angular 10 中,一切正常,但是當我將我的項目從 angular 10 升級到angular 13 時,我收到了一個失敗,如下圖所示
下面是我的 TokenStorage class 代碼:
import { Injectable } from '@angular/core';
const TOKEN_KEY = 'AuthToken';
const USERNAME_KEY = 'AuthUsername';
const AUTHORITIES_KEY = 'AuthAuthorities';
@Injectable()
export class TokenStorage {
roles: string[] = [];
constructor(){}
signOut(){
window.sessionStorage.removeItem(TOKEN_KEY);
window.sessionStorage.clear();
this.reloadPage();
}
public saveToken(token: string){
window.sessionStorage.removeItem(TOKEN_KEY);
window.sessionStorage.setItem(TOKEN_KEY, token);
}
public getToken(): string {
return sessionStorage.getItem(TOKEN_KEY);
}
public saveLogin(login: string){
window.sessionStorage.removeItem(USERNAME_KEY);
window.sessionStorage.setItem(USERNAME_KEY, login);
}
public getLogin(): string{
return sessionStorage.getItem(USERNAME_KEY);
}
public saveAuthority(authorities: string[]){
window.sessionStorage.removeItem(AUTHORITIES_KEY);
window.sessionStorage.setItem(AUTHORITIES_KEY, JSON.stringify(authorities))
}
public getAuthority(): string[] {
this.roles = []
if (sessionStorage.getItem(TOKEN_KEY)) {
JSON.parse(sessionStorage.getItem(AUTHORITIES_KEY)!).forEach(authority => {
this.roles.push(authority.authority);
});
}
return this.roles;
}
public isUserSignedIn() : boolean {
if(this.getToken()){
return true;
}
return false;
}
reloadPage(): void{
window.location.reload();
}
}
這是攔截器類代碼:
import { Injectable } from '@angular/core';
import {HttpInterceptor, HttpRequest, HttpHandler, HttpSentEvent, HttpHeaderResponse, HttpProgressEvent,
HttpResponse, HttpUserEvent, HttpErrorResponse} from '@angular/common/http';
import { Observable } from 'rxjs';
import { Router } from '@angular/router';
import {TokenStorage} from './token.storage';
import {tap} from "rxjs/operators";
const TOKEN_HEADER_KEY = 'Authorization';
@Injectable()
export class Interceptor implements HttpInterceptor {
constructor(private token: TokenStorage, private router: Router) { }
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any>> {
let authReq = req;
if (this.token.getToken() != null) {
authReq = req.clone({ headers: req.headers.set(TOKEN_HEADER_KEY, 'Bearer ' + this.token.getToken())});
}
return next.handle(authReq).pipe( tap(() => {},
(err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status !== 401) {
return;
}
}
}));
}
}
這是 auth.service 代碼:
import { Observable, throwError } from 'rxjs';
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
@Injectable()
export class AuthService {
private watkrewUrl = "http://localhost:8080/";
constructor(private _http: HttpClient) {
}
login(login: string, password: string): Observable<any> {
const credentials = {login: login, password: password};
return this._http.post<any>(this.watkrewUrl + "signin", credentials).pipe(
catchError((err: HttpErrorResponse) => {
return throwError(err.error.message);
console.log(err.message)
}
))
}
register(login: string, password: string, email: string, name: string, surname: string, role: string): Observable<any>{
const signupForm = {login: login, password: password, email:email, name:name, surname: surname, role: role}
return this._http.post<any>(this.watkrewUrl + "signup", signupForm).pipe(
catchError((err: HttpErrorResponse)=> {
return throwError(err.error.message);
})
)
}
}
有誰知道如何解決這個問題?
SessionStorage.getKey
返回string | null
string | null
。
但是,您的TokenStorage.getToken
方法會根據您的簽名返回string
。
如果您確定 session 存儲始終包含此密鑰,則可以在不更改TokenStorage.getToken
簽名的情況下執行以下操作之一。 a) 轉換string | null
string | null
到像sessionStorage.getItem(TOKEN_KEY) as string
string
b) 檢查null
如果值為null
則拋出錯誤
public getToken(): string {
const value = sessionStorage.getItem(TOKEN_KEY);
if (!value) {
throw Error('Type a message here');
}
return value;
}
否則,您必須將TokenStorage.getToken
返回類型更改為string | null
string | null
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.