【发布时间】:2020-06-09 03:57:17
【问题描述】:
我正在使用身份服务器 4 和 Angular 9。我已经设置了身份服务器,并且能够在我的 Angular 应用程序中成功登录,但是由于未定义,我无法访问用户配置文件、用户名等。
但是在使用 oidc 用户登录 angular auth-callback 组件后,我可以使用 usermanager 设置获取所有用户详细信息(id_token、访问令牌等),但在组件中我不能。登录后,用户对象为空或未定义,但是当我在成功登录后刷新页面时,我可以检索用户名。
我不知道我的角度代码有什么问题。
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"]);
}
}
【问题讨论】: