使用Identity Server 4和OIDC客户端进行无声登录

6
我正在尝试在 Angular 2 中使用 oidc-client 实现静默登录。
如何使用 oidc client 静默检查用户是否已登录(idsvr4)并显示登录详细信息。
下面的代码可以工作,但是我需要刷新页面。
idsvr4 客户端。
  // JavaScript Client
            new Client
            {
                ClientId = "js",
                ClientName = "JavaScript Client",
                AllowedGrantTypes = GrantTypes.Implicit,
                AllowAccessTokensViaBrowser = true,


                RedirectUris = { "http://localhost:5002/callback.html" },

                PostLogoutRedirectUris = { "http://localhost:5002/index.html" },
                AllowedCorsOrigins = { "http://localhost:5002" },

                AllowedScopes =
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    "api1",

                },
                    RequireConsent=false,
                AllowOfflineAccess = true
            }

客户端代码

    var config = {
     authority: "http://localhost:5000",
    client_id: "js",
    redirect_uri: "http://localhost:5002/callback.html",
    silent_redirect_uri: "http://localhost:5002/callback.html",
    response_type: "id_token token",
    scope: "openid profile api1 offline_access",
    post_logout_redirect_uri: "http://localhost:5002/index.html",



    // Number of seconds before the token expires to trigger
    // the `tokenExpiring` event
    accessTokenExpiringNotificationTime: 4,

    // Do we want to renew the access token automatically when it's
    // about to expire?
    automaticSilentRenew: false,
   
    // Do we want to filter OIDC protocal-specific claims from the response?
    filterProtocolClaims: false,

    // use localStorage
    userStore: new Oidc.WebStorageStateStore({ store: window.localStorage })
    };
    var mgr = new Oidc.UserManager(config);


    // You can hook a logger to the library.
    // Conveniently, the methods exposed by the logger match
     // the `console` object
    Oidc.Log.logger = console;

    // When a user logs in successfully or a token is renewed, the `userLoaded`
    // event is fired. the `addUserLoaded` method allows to register a callback to
    // that event
    mgr.events.addUserLoaded(function (loadedUser) {
    console.log("$$$$$$$$$$$$$$$$$$$$$$$ added");
    });

    // Same mechanism for when the automatic renewal of a token fails
    mgr.events.addSilentRenewError(function (error) {
    console.error('$$$$$$$$$$$$$$$$$$$$$$$ error while renewing the access    token', error);
    });

    // When the automatic session management feature detects a change in
    // the user session state, the `userSignedOut` event is fired.
    mgr.events.addUserSignedOut(function () {
    alert('The user has signed out');
    });

    mgr.getUser().then(function (user) {
    if (user) {
        log("User logged in", user.profile);
    }
    else {
        log("User not logged in");
       // log("*****************************************************");
        mgr.signinSilent()
        .then(function (newUser) {
            console.log("doneeeeeeeeeeeeeeeeeeeee");
            console.log(newUser);
            console.log(newUser.profile);
        }).catch(function (e) {
            console.log("========  " + e);
        });;
        mgr.signinSilentCallback().then(function (newUser) {
        console.log("doneeeeeeeeeeeeeeeeeeeee");
        console.log(newUser);
        console.log(newUser.profile);
    }).catch(function (e) {
            console.log("&&&&&&&&&&&&  "+e);
        });

    }


    });

无论是在silentSignIn的哪种方法中,都没有返回任何用户。

我想要获取用户是否已登录,并在客户端打开时立即检索信息。

如果在Angular 2中有更好的方法,则最好使用它。


我遇到了类似的问题。你解决了吗? - SteveL
你如何使用 automaticSilentRenew: true 来完成这个任务? - William Lohan
我有同样的问题,当执行SilenceRenew时,有时API会返回401错误,导致我的应用程序“重新加载”页面。 - Avtandil Kavrelishvili
1个回答

0

我曾经遇到过同样的问题。我通过使用以下的signin()方法并管理登录响应过程来解决了它:

function signin() {
    manager.createSigninRequest().then(function (req) {
        window.location = req.url;
    }).catch(function (err) {
        log(err);
    });
}


manager.processSigninResponse().then(function (response) {
    log("signin response success", response);
}).catch(function (err) {

});

manager.events.addUserLoaded(function (user) {
    manager.getUser().then(function () {
        log("User logged in", user.profile);
    });
});



function api() {
      mgr.getUser().then(function (user) {
    var url = "http://localhost:5001/identity";

    var xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.onload = function () {
        log(xhr.status, JSON.parse(xhr.responseText));
    }
    xhr.setRequestHeader("Authorization", "Bearer " + idToken);
    xhr.send();
       });
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接