首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Angular 5中,静默刷新不适用于OIDC-client

在Angular 5中,静默刷新不适用于OIDC-client
EN

Stack Overflow用户
提问于 2018-02-14 10:06:11
回答 5查看 14.5K关注 0票数 9

我对oidc-client的静默刷新有问题。登录工作正常,我可以获得一个令牌。但是,静默刷新不会触发,什么也不会发生。当我订阅检查令牌过期的方法(下面authservice.ts中subscribeevents中的方法)时,这些方法从不触发-即使令牌已经过期,isLoggedIn()方法也始终返回true。

下面是我的代码:

代码语言:javascript
复制
import { Component, OnInit } from '@angular/core';
import { UserManager } from 'oidc-client';
import { getClientSettings } from '../openIdConnectConfig';
import { AuthService } from '../services/auth.service';
    
@Component({
    selector: 'app-silentrefresh',
    templateUrl: './silentrefresh.component.html',
    styleUrls: ['./silentrefresh.component.css']
})
export class SilentRefreshComponent implements OnInit {
    constructor(private _authService:AuthService) {
    }
    
    ngOnInit() {
        this._authService.refreshCallBack();
    }
}

然后是我的authservice:

代码语言:javascript
复制
import { UserManagerSettings, UserManager, User } from 'oidc-client';
import { Injectable } from '@angular/core';
import { getClientSettings } from '../openIdConnectConfig';
    
@Injectable()
export class AuthService {

    private _manager = new UserManager(getClientSettings());
    private _user: User = null;

    constructor() {
        this._manager.getUser().then(user => {
            this._user = user;
        });

        this._manager.events.addUserLoaded(user => {
            this._user = user;
        });

        this.subscribeevents();
    }

    public isLoggedIn(): boolean {
        return this._user != null && !this._user.expired;
    }

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

    public subscribeevents(): void {
        this._manager.events.addSilentRenewError(() => {
            console.log("error SilentRenew");
        });

        this._manager.events.addAccessTokenExpiring(() => {
            console.log("access token expiring");
        });

        this._manager.events.addAccessTokenExpired(() => {
            console.log("access token expired");
        });
    }

    public refreshCallBack(): void {
        console.log("start refresh callback");
        this._manager.signinSilentCallback()
            .then(data => { console.log("suucess callback") })
            .catch(err => {
                console.log("err callback");
            });
        console.log("end refresh callback");
    }

    getUser(): any {
        return this._user;
    }

    getName(): any {
        return this._user.profile.name;
    }

    getAuthorizationHeaderValue(): string {
        return `${this._user.token_type} ${this._user.access_token}`;
    }

    startAuthentication(): Promise<void> {
        return this._manager.signinRedirect();
    }

    completeAuthentication(): Promise<void> {
        return this._manager.signinRedirectCallback().then(user => {
            this._user = user;
        });
    }
}

和我的配置:

代码语言:javascript
复制
import { UserManagerSettings } from "oidc-client";

export function getClientSettings(): UserManagerSettings {
    return {
        authority: 'https://login.microsoftonline.com/136544d9-038e-4646-afff-10accb370679',
        client_id: '257b6c36-1168-4aac-be93-6f2cd81cec43',
        redirect_uri: 'http://localhost:4200/auth-callback',
        //redirect_uri: 'https://demoazureadconnectangular5.azurewebsites.net/auth-callback',
        post_logout_redirect_uri: 'http://localhost:4200/',
        //post_logout_redirect_uri: 'https://demoazureadconnectangular5.azurewebsites.net/',
        response_type: "id_token",
        scope: "openid profile",
        filterProtocolClaims: true,
        loadUserInfo: true,
        automaticSilentRenew: true,
        silent_redirect_uri: 'http://localhost:4200/assets/silentrefresh',
        metadata: {
            issuer: "https://sts.windows.net/136544d9-038e-4646-afff-10accb370679/",
            authorization_endpoint: "https://login.microsoftonline.com/136544d9-038e-4646-afff-10accb370679/oauth2/authorize",
            token_endpoint: "https://login.microsoftonline.com/136544d9-038e-4646-afff-10accb370679/oauth2/token",
            //jwks_uri: "https://login.microsoftonline.com/common/discovery/keys",
            jwks_uri: "http://localhost:4200/assets/keys.json",
            //jwks_uri: "https://demoazureadconnectangular5.azurewebsites.net/assets/keys.json",
            //jwks_uri: "http://localhost:50586/api/keys",
            signingKeys: [{ "ApiAccessKey": "NgixniZ0S1JHxo7GPEZYa38OBTxSA98AqJKDX5XqsJ8=" }]
        }
    };
}

我还尝试使用静态页面,如下所示:

代码语言:javascript
复制
<head>
    <title></title>
</head>

<body>
    <script src="oidc-client.min.js"></script>
    <script>
        var usermanager = UserManager().signinSilentCallback()
            .catch((err) => {
                console.log(err);
            });
    </script>
</body>

它也从来没有发射过

为了进行测试,我将ID令牌过期时间更改为10分钟。我使用Azure AD Connect (Azure中的Open Id Connect ),而微软说它与Open ID Connect标准不完全兼容……所以我不知道它是在我这边还是在Azure这边。

有人能帮我解决这个问题吗?

EN

回答 5

Stack Overflow用户

发布于 2018-06-26 15:16:50

问题是你不是从azure AD请求access_token,而是从id_token请求。您必须将response_type设置为id_token token才能同时获取这两个令牌。此更改还需要更多的参数。例如,后端的资源。我在这里回答了类似的问题。我也在使用Angular 5和oidc客户端。在https://github.com/IdentityModel/oidc-client-js/issues/504#issuecomment-400056662之前,https://stackoverflow.com/a/50922730/8081009和我在这里回答你,这里是你需要设置的让静默续订工作的东西。

代码语言:javascript
复制
includeIdTokenInSilentRenew: true
extraQueryParams: {
      resource: '10282f28-36ed-4257-a853-1bf404996b18'
}
response_type: 'id_token token',
scope: 'openid'
loadUserInfo: false,
automaticSilentRenew: true,
silent_redirect_uri: `${window.location.origin}/silent-refresh.html`,
metadataUrl: 'https://login.microsoftonline.com/YOUR_TENANT_NAME.onmicrosoft.com/.well-known/openid-configuration',
signingKeys: [
    add here keys from link below
]

https://login.microsoftonline.com/common/discovery/keys

我还使用了不同的静态页面作为回调端点的静默更新,因为这样用户就不会注意到任何事情。这个页面是最低限度的,所以oidc不会将整个angular应用程序加载到隐藏的iframe中,因为它用于静默更新。所以建议这样做会更有效率。

代码语言:javascript
复制
<head>
  <title></title>
</head>

<body>
  <script src="assets/oidc-client.min.js"></script>
  <script>
    new Oidc.UserManager().signinSilentCallback()
      .catch((err) => {
        console.log(err);
      });
  </script>
</body>
票数 3
EN

Stack Overflow用户

发布于 2020-07-12 16:53:10

  1. 检查数据库中的重定向URI是否正确。

  1. 检查您已在angular.json文件中添加了以下内容:

..。"assets":"src/assets","silent-refresh.html","oidc-client.min.js“.....,...

  1. Check silent-refresh.html

不能创建多个UserManager实例的

  1. 检查

  1. 你可以选择任何一种方式-- automaticSilentRenew: false或者automaticSilentRenew: true,我推荐使用automaticSilentRenew: false并在过期时触发事件。

https://github.com/IdentityModel/oidc-client-js/wiki

public renewToken() { return this.manager.signinSilent().then(u => { this.user = u;}).catch(er => { console.log(er);});} this.manager.events.addAccessTokenExpiring(x => {console.log(‘访问令牌过期事件’);this.renewToken().then(u => {console.log(‘访问令牌过期事件续订成功’);});

如果上述操作不起作用,请检查identity server代码。

身份服务器代码

启动

代码语言:javascript
复制
services.AddIdentityServer(options =>
    {
        options.Authentication.CookieLifetime = TimeSpan.FromDays(30);
        options.Authentication.CookieSlidingExpiration = true;
    });
services.AddAuthentication(x => x.DefaultAuthenticateScheme = IdentityServerConstants.DefaultCookieAuthenticationScheme);

注销

代码语言:javascript
复制
await HttpContext.SignOutAsync(IdentityServer4.IdentityServerConstants.DefaultCookieAuthenticationScheme);

感谢https://github.com/IdentityModel/oidc-client-js/issues/911#issuecomment-617724445

票数 3
EN

Stack Overflow用户

发布于 2018-07-13 19:28:29

最简单的原因可能是,在identity server配置中没有添加静默续订url作为重定向url。

在identity server数据库中,客户端的重定向urls应如下所示

代码语言:javascript
复制
redirectUrls: [http://localhost:4200/assets/silentrefresh, http://localhost:4200/auth-callback]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48778603

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档