简体   繁体   中英

Problem with authorization in Angular 13 in web-app project

I have a problem with authorization in my project in angular 13 version. In angular 10 everything was ok but when I upgraded my project from angular 10 to angular 13 I received a fail like on the photo below enter image description here

And below is my TokenStorage class code:

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();
    }
}

Here is Interceptorclass code:

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;
       }
     }
   }));

  }

}

And here is auth.service code:

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);
      })
    )
  }
}

Does anyone have any idea how to fix that issue?

SessionStorage.getKey returns string | null string | null .
However, your TokenStorage.getToken method returns string according to your signature.

If you're sure the session storage always contains this key, you could do one of the following items without changing the TokenStorage.getToken signature. a) cast a string | null string | null to string like sessionStorage.getItem(TOKEN_KEY) as string
b) check for null and throw an error if the value is null

    public getToken(): string {
        const value = sessionStorage.getItem(TOKEN_KEY);
        if (!value) {
            throw Error('Type a message here');
        }
        return value;
    }

Otherwise, you'd have to change TokenStorage.getToken return type to string | null string | null .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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