刷新页面时出现角度12错误401 [英] Angular 12 error 401 when page is refreshed

查看:28
本文介绍了刷新页面时出现角度12错误401的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ANGLE 12+Spring boot(使用基本身份验证Spring安全性)创建一个登录表单。当用户登录时,他们将被重定向到主页,该主页具有如下所示的CRUD操作:

但是,当页面刷新或重新加载时,它会返回到此状态(观察控制台,即使我已经登录,它也会返回401未授权状态):

这是我来自ANGLE的代码

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable({
  providedIn: 'root',
})
export class AuthService {
  USER_NAME_SESSION_ATTRIBUTE_NAME = 'authenticatedUser';

  public username: String = '';
  public password: String = '';

  constructor(private http: HttpClient) {}

  authenticationService(username: String, password: String) {
    return this.http
      .get(`http://localhost:8081/webapp/login/`, {
        headers: {
          Authorization: this.createBasicAuthToken(username, password),
        },
      })
      .pipe(
        map((res) => {
          this.username = username;
          this.password = password;
          this.registerSuccessfulLogin(username, password);
        })
      );
  }

  createBasicAuthToken(username: String, password: String) {
    return 'Basic ' + window.btoa(username + ':' + password);
  }

  registerSuccessfulLogin(username: any, password: String) {
    sessionStorage.setItem(this.USER_NAME_SESSION_ATTRIBUTE_NAME, username);
  }

  isUserLoggedIn() {
    let user = sessionStorage.getItem(this.USER_NAME_SESSION_ATTRIBUTE_NAME);
    if (user === null) return false;
    return true;
  }

}

拦截器:

import { Injectable } from '@angular/core';
import {
  HttpInterceptor,
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpHeaders,
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable({
  providedIn: 'root',
})
export class HttpinterceptorService implements HttpInterceptor {
  USER_NAME_SESSION_ATTRIBUTE_NAME = 'authenticatedUser';

  constructor(private authenticationService: AuthService) {}
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    if (
      this.authenticationService.isUserLoggedIn() &&
      req.url.indexOf('basicauth') === -1
    ) {
      const authReq = req.clone({
        headers: new HttpHeaders({
          'Content-Type': 'application/json',
          Authorization: `Basic ${window.btoa(
            this.authenticationService.username +
              ':' +
              this.authenticationService.password
          )}`,
        }),
      });
      return next.handle(authReq);
    } else {
      return next.handle(req);
    }
  }
}

推荐答案

问题在您的AuthService中。

  1. 当用户成功登录时,您没有在任何地方存储密码。
  2. 然后当您继续刷新此页面时,您的isUserLoggedIn仅在会话存储[+]中找到username,而且您没有同时更新AuthService中的username and password

因此,intercepterthis.authenticationService.username/password

中找不到任何usernamepassword
 createBasicAuthToken(username: String, password: String) {
    return 'Basic ' + window.btoa(username + ':' + password);
  }

  registerSuccessfulLogin(username: any, password: String) {
    // HERE ONLY username is stored
    sessionStorage.setItem(this.USER_NAME_SESSION_ATTRIBUTE_NAME, username);
  }

  isUserLoggedIn() {
    // HERE username and password for this service should be updated.
    let user = sessionStorage.getItem(this.USER_NAME_SESSION_ATTRIBUTE_NAME);
    if (user === null) return false;
    return true;
  }

无论您是要存储简单密码还是以加密格式存储密码,您都可以选择以某种方式存储这些密码。

这篇关于刷新页面时出现角度12错误401的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆