angular 的安全性问题 - 身份验证

Problem with security on angular - authenticate

提问人:GotaKev 提问时间:11/9/2023 更新时间:11/10/2023 访问量:65

问:

我使用弹簧和角度。目前,我正在对我的应用程序进行身份验证。 对于春天来说,一切正常,但是对于angular,我有一个问题。

这是我的代码:

[HTML全文]

    <div class="flex flex-col items-center justify-center px-6 py-8 mx-auto md:h-screen lg:py-0">
        <div class="w-full bg-white rounded-lg shadow dark:border md:mt-0 sm:max-w-md xl:p-0 dark:bg-gray-800 dark:border-gray-700">
            <div class="p-6 space-y-4 md:space-y-6 sm:p-8">
                <h1 class="text-xl font-bold leading-tight tracking-tight text-gray-900 md:text-2xl dark:text-white">
                    Sign in to your account
                </h1>
                <form class="space-y-4 md:space-y-6" (submit)="login()">
                    <div>
                        <label for="username" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Your Username</label>
                        <input type="text" name="username" id="username" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="Pseudo123" required="" [(ngModel)]="credentials.username">
                    </div>
                    <div>
                        <label for="password" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Password</label>
                        <input type="password" name="password" id="password" placeholder="••••••••" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" required="" [(ngModel)]="credentials.password">
                    </div>
                    <div class="flex items-center justify-between">
                        <div class="flex items-start">
                            <div class="flex items-center h-5">
                              <input id="remember" aria-describedby="remember" type="checkbox" class="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-primary-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-primary-600 dark:ring-offset-gray-800" required="">
                            </div>
                            <div class="ml-3 text-sm">
                              <label for="remember" class="text-gray-500 dark:text-gray-300">Remember me</label>
                            </div>
                        </div>
                        <a href="#" class="text-sm font-medium text-primary-600 hover:underline dark:text-primary-500">Forgot password?</a>
                    </div>
                    <button type="submit" class="w-full text-black bg-primary-600 hover:bg-primary-700 focus:ring-4 focus:outline-none focus:ring-primary-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800">Sign in</button>
                    <p class="text-sm font-light text-gray-500 dark:text-gray-400">
                        Don’t have an account yet? <a href="#" class="font-medium text-primary-600 hover:underline dark:text-primary-500">Sign up</a>
                    </p>
                </form>
            </div>
        </div>
    </div>
  </section>

我的登录页面的服务:

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AppService } from '../services/app.service';
import { UserService } from '../services/user.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {
  credentials = {username:'', password:''}
  constructor(private appService:AppService,private httplClient:HttpClient,private router:Router,private userService:UserService) { }
  login(){
    console.log("username="+this.credentials.username+" password="+this.credentials.password);
    this.appService.authenticate(this.credentials,()=>{this.router.navigateByUrl("/espace-compte")}); la page, pour la fonctionnalité.
    return false;
  }

}

我的应用程序的服务

在这里,我只需检索信息以将其发送到身份验证功能

import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root'
})
export class AppService {
  authenticated=false;
  responseAll: any;
  isAdmin=false;
  str:any;
  constructor(private httpClient:HttpClient) { }

  authenticate(credentials:any,callback:any){
      const headers = new HttpHeaders(
      credentials ? {
        'Content-Type': 'application/json',
       
        authorization : 'Basic ' + btoa(credentials.username+ ':' + credentials.password)
      } : {}   
      );
      this.str = JSON.stringify(headers);
      //this.str = JSON.stringify(headers, null, 4); // (Optional) beautiful indented output.
      console.log(this.str); // Logs output to dev tools console.
      this.httpClient.get(environment.apiBaseUrl+'login/user',{headers:headers}).subscribe(response =>{
        this.responseAll = response;
        console.log("connexion="+this.responseAll);
        if(this.responseAll['username']){
          this.authenticated = true;
          console.log("true or false="+this.authenticated);
          console.log("username="+(this.responseAll['username']))
          for(let i=0;i<this.responseAll['roles'].length;i++){
            console.log("id===="+this.responseAll['roles'][i]['idRole']);
            if(this.responseAll['roles'][i]['idRole']==1){
              this.isAdmin = true;
            }
          }
        }else{
          this.authenticated = false;
        }
        return callback && callback();
      })


  }
}

在这里,我在点击连接期间进行铬检查的问题

username=GotaKev password=1234
app.service.ts:25 {"normalizedNames":{},"lazyUpdate":null}
app.service.ts:28 connexion=null
core.mjs:11483  ERROR TypeError: Cannot read properties of null (reading 'username')
   at Object.next (app.service.ts:29:28)
   at ConsumerObserver.next (Subscriber.js:91:33)
   at SafeSubscriber._next (Subscriber.js:60:26)
   at SafeSubscriber.next (Subscriber.js:31:18)
   at map.js:7:24
   at OperatorSubscriber._next (OperatorSubscriber.js:13:21)
   at OperatorSubscriber.next (Subscriber.js:31:18)
   at filter.js:6:128
   at OperatorSubscriber._next (OperatorSubscriber.js:13:21)
   at OperatorSubscriber.next (Subscriber.js:31:18)
handleError @ core.mjs:11483 ```


I don't understand the error and I don't know why it doesn't take these identifiers. In the back-end everything works great.
Please if you have idea, thanks
Angular Spring 身份验证 安全性

评论


答:

1赞 moh 11/9/2023 #1

您遇到的错误消息“无法读取 null 的属性(读取'username')”,表明代码正在尝试访问为 null 或未定义的对象的“username”属性。在您的代码中,当您尝试访问 this.responseAll 对象的“username”属性时,似乎会发生这种情况。

若要解决此问题,应在尝试访问其属性之前检查 this.responseAll 对象是否为 null 或未定义。您可以通过添加条件检查来执行此操作。

下面是代码的更新版本,其中包含条件检查以防止错误:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root'
})
export class AppService {
  authenticated = false;
  isAdmin = false;
  responseAll: any;

  constructor(private httpClient: HttpClient) {}

  async authenticate(credentials: any): Promise<boolean> {
    try {
      if (!credentials) {
        return false;
      }

      const headers = new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': `Basic ${btoa(credentials.username + ':' + credentials.password)}`
      });

      const response: any = await this.httpClient.get(environment.apiBaseUrl + 'login/user', { headers }).toPromise();

      if (response && response.username) {
        this.authenticated = true;
        this.responseAll = response;

        for (const role of this.responseAll.roles) {
          if (role.idRole === 1) {
            this.isAdmin = true;
            break;
          }
        }

        return true;
      }

      this.authenticated = false;
      return false;
    } catch (error) {
      console.error('Error while authenticating:', error);
      return false;
    }
  }
}

评论

0赞 GotaKev 11/9/2023
我已经这样做了,并且 responseAll est null
0赞 moh 11/9/2023
@GotaKev即使添加条件,您仍然收到错误吗?
0赞 GotaKev 11/9/2023
是的,即使您添加条件,我仍然收到错误。username=GotaKev password=1234 app.service.ts:25 {"normalizedNames":{},"lazyUpdate":null} app.service.ts:28 connexion=null
0赞 GotaKev 11/9/2023
我被重定向到另一个页面,但它无法让我登录
0赞 moh 11/10/2023
@GotaKev我已经更新了上面的代码。请尝试