【问题标题】:angular+oidc-client: getUser() always returns nullangular+oidc-client:getUser() 总是返回 null
【发布时间】:2021-06-03 04:37:34
【问题描述】:

我在我的 Angular 项目中使用 oidc-client。如果用户对象不为空,我在 app.component.ts 中编写了以下代码以将用户重定向到主页。但是即使成功登录,用户对象也始终为空。我正在使用 microsoft azure 进行身份验证。

app.component.ts

async ngOnInit() {
    await this.authService.getUser().then(user => {
        console.log(user) // always returns null even after login
        if (user) {
            this.router.navigate(['/home']);
        }
    });
}

login() {
    this.authService.signinRedirect();
}

AuthenticationService.ts

export class AuthenticationService {
    
    private userManager: UserManager;
    constructor(settings: Settings) {
        this.userManager = new UserManager(settings);
    }

    public signinRedirect() {
       this.userManager.signinRedirect();
    }

    public getUser() {
        return this.userManager.getUser();
    }
}

成功登录后,我在名为 oidc.user.xxxxxxx 的本地/会话存储中没有看到任何 key:val 对。

此外,我还对一些示例内部应用程序进行了交叉检查。成功登录后,oidc api 将触发对令牌端点的调用。在我的情况下,这个端点没有被调用。

可能缺少什么?我做错了什么?

【问题讨论】:

  • 在哪个模块中提供了AuthenticationService,也可以贴出UserManager代码吗?
  • 我只有一个模块。 UserManager 来自 oidc-client 库。

标签: angular oidc-client


【解决方案1】:

在 app.component.ts 中注册登录重定向回调解决了这个问题。

async ngOnInit() {
if (window.location.href.includes('code')) { // without this if condition I am getting an error saying no state in response. not sure if there is a better way.
     this.authService.signinRedirectCallback();
}

await this.authService.getUser().then(user => {
    console.log(user) // always returns null even after login
    if (user) {
        this.router.navigate(['/home']);
    }
});

}

【讨论】:

    猜你喜欢
    • 2014-03-04
    • 2016-11-02
    • 2014-05-06
    • 2012-06-05
    • 2014-05-30
    • 2014-02-23
    • 2017-10-12
    • 2013-08-16
    • 2016-03-28
    相关资源
    最近更新 更多