TypeError:无法使用Idenity Server 4在Angular中读取null的属性“配置文件" TypeError:无法读取Angular中的null的属性“配置文件" [英] TypeError: Cannot read property 'profile' of null TypeError: Cannot read property 'profile' of null in Angular using idenity Server 4

查看:130
本文介绍了TypeError:无法使用Idenity Server 4在Angular中读取null的属性“配置文件" TypeError:无法读取Angular中的null的属性“配置文件"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用身份服务器4和angular9.我已经安装了身份服务器,并且能够在我的angular应用程序中成功登录,但是由于无法定义,所以我无法访问用户个人资料,用户名等.

I am using identity server 4 and angular 9. i have setup the identity server and i was able to login successfully in my angular application but, i can't access the user profile, username etc. as i get undefined.

但是使用oidc用户登录有角度的auth-callback组件后,usermanager设置我可以使用获取所有用户详细信息(id_token,访问令牌等),但是在组件i中却无法.登录后,用户对象为null或未定义,但是当成功登录后刷新页面时,我可以检索用户名.

But after login in the angular auth-callback component using the oidc user, usermanager setting i was able using get all the user details (id_token, access token etc) but in component i could not. after login the user object is null or undefined but when i refresh my page after successful login i can retrieve the username.

我不知道我的角度代码有什么问题.

I don't know what is wrong with my angular code.

my authservice code goes here

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { catchError } from 'rxjs/operators';
    import { UserManager, UserManagerSettings, User } from 'oidc-client';
    import { BehaviorSubject } from 'rxjs'; 

    import { AppconfigService } from '../Shared/appconfig.service';
    import { getClientSettings } from '../Shared/ClientSettings';


    @Injectable({
      providedIn: 'root'
    })

    export class AuthService extends AppconfigService {
    // Observable navItem source
    private _authNavStatusSource = new BehaviorSubject<boolean>(false);
    // Observable navItem stream
      authNavStatus$ = this._authNavStatusSource.asObservable();

    private manager = new UserManager(getClientSettings());
    private user: User| null;

    constructor(private http: HttpClient, private configService: AppconfigService) { 
    super();     
    this.getUser();
      }

      getUser() {
      this.manager.getUser().then(user => { 
      this.user = user;      
      this._authNavStatusSource.next(this.isAuthenticated());
      });
     return this.user;
     }

      login() { 
        return this.manager.signinRedirect();   
      }

  async completeAuthentication() {
      this.user = await this.manager.signinRedirectCallback();
      this._authNavStatusSource.next(this.isAuthenticated());
    }  

    // async completeAuthentication(): Promise<void> {
    //     return this.manager.signinRedirectCallback().then(user => {
    //         this.user = user;
    //     });
    // }

    signinSilentCallback(){
    this.manager.signinSilentCallback()
    .catch((err) => {
      console.log(err);
      });
      }  

      register(userRegistration: any) {    
    return this.http.post(this.configService.authApiURI + '/account',         
    userRegistration).pipe(catchError(this.handleError));
    }

  isAuthenticated(): boolean {
    return (this.user != null && !this.user.expired);
  }

  get authorizationHeaderValue(): string {
    return `${this.user.token_type} ${this.user.access_token}`;
  }

      // get name(): string {
      //   return this.user !== null ? this.user !== undefined : '';
      // }

      getClaims(): any {
        return this.user.profile;
      }

      get name(): string {

    if (this.user !== null && this.user !== undefined){
    console.log(this.user);
      return  this.user.profile.name;
    } else {
      return null;
    }
    }

      async signout() {
        await this.manager.signoutRedirect();
      }
    } 

应用程序组件

    import { Component, OnInit, OnDestroy } from '@angular/core';
    import { Subscription, BehaviorSubject, Observable } from 'rxjs';
    import { User, UserManager } from 'oidc-client';
    import { AuthService } from './Services/auth.services';
    import { TopsecretService } from './Services/topsecret.service';
    import { Router } from '@angular/router';
    import { HttpClient } from '@angular/common/http';
    import { AppconfigService } from './Shared/appconfig.service';
    import { getClientSettings } from './Shared/ClientSettings';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit, OnDestroy {
      name: string;
      isAuthenticated: boolean;
    subscription:Subscription;

    private manager = new UserManager(getClientSettings());
    private _authNavStatusSource = new BehaviorSubject<boolean>(false);
    title = 'Oyo State Signage & Advertisement Agency [OYSAA]';
    constructor(private http: HttpClient,private appConfig: AppconfigService,private authService:AuthService, private router: Router) {
   this.getUser();
      }
      ngOnInit() {
    //this also give error
    console.log(this.authService.name);

    //this also give error
    console.log(this.authService.authorizationHeaderValue);
      } 

    getUser(): string {
    this.manager.getUser().then(user => { 

      /// I have get the error here but if i refesh the page 
      this.name = user.profile.name;    
      this._authNavStatusSource.next(this.authService.isAuthenticated());
    });
    return this.name;
    }

    ngOnDestroy() {
    // prevent memory leak when component is destroyed
    this.subscription.unsubscribe();
    }
    }

客户端设置

    import { UserManagerSettings } from 'oidc-client';

    export function getClientSettings(): UserManagerSettings {
    return {
      authority: 'https://localhost:5000',
      client_id: 'oysaafrontend',
      redirect_uri: 'http://localhost:4200/auth-callback',
      post_logout_redirect_uri: 'http://localhost:4200/',
      response_type:"id_token token",
      scope:"openid profile email address phone role",
      filterProtocolClaims: true,
      loadUserInfo: true,
      automaticSilentRenew: true,
      silent_redirect_uri: 'http://localhost:4200/silent-refresh.html'
      //silent_redirect_uri: 'https://oysaa.azurewebsites.net/silent-refresh.html'
      };
    }

身份验证回调

    import { Component, OnInit } from '@angular/core';
    import { AuthService } from 'src/app/Services/auth.services';
    import { Router, ActivatedRoute } from '@angular/router';
    import { Subscription } from 'rxjs';
    import { User } from 'oidc-client';

    @Component({
    selector: 'app-auth-callback',
      templateUrl: './auth-callback.component.html',
      styleUrls: ['./auth-callback.component.css']
    })
    export class AuthCallbackComponent implements OnInit {
     error: boolean;
     user: User | null;
      constructor(private authService: AuthService, private router: Router, private route: ActivatedRoute) {}

    async ngOnInit() {

    // check for error
    // if (this.route.snapshot.fragment.indexOf('') >= 0) {
    //    this.error=true; 
    //    return;    
    //  }     
    await this.authService.completeAuthentication();
    this.router.navigate(["/admin/dashboard"]);    

      }
    }

推荐答案

,您可以使用 angular-oauth2-oidc 可以帮助您解决问题.将令牌保存在会话/本地存储中.获取,保存和提供用户个人资料数据.

you can use angular-oauth2-oidc which help you with your problem. save tokens in session/local storage. fetch,save and serve user profile data.

这篇关于TypeError:无法使用Idenity Server 4在Angular中读取null的属性“配置文件" TypeError:无法读取Angular中的null的属性“配置文件"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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