1. 程式人生 > >IdentityServer4 登錄成功後,跳轉到原來頁面

IdentityServer4 登錄成功後,跳轉到原來頁面

localhost token

IdentityServer4 登錄成功後,默認會跳轉到Config.Client配置的RedirectUris地址http://localhost:5003/callback.html,用於獲取 Token,比如跳轉後的地址:

http://localhost:5003/callback.html#id_token=eyJhbGciOiJSUzI1NiIsImtpZCI6IjkwYWRmOTliMDhmODExMjBiMzdlMWI1NzVmMDliODcwIiwidHlwIjoiSldUIn0.eyJuYmYiOjE0OTQ2NjA3ODQsImV4cCI6MTQ5NDY2MTA4NCwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAxIiwiYXVkIjoiaDUiLCJub25jZSI6IjQ0OTYwZDQzYjgwNTQzOWJiYjI4NWFkZjJiYjFkNDA0IiwiaWF0IjoxNDk0NjYwNzg0LCJhdF9oYXNoIjoieE9Lb0V1VnlMNHdXUVhsbllaak5udyIsInNpZCI6ImMzYzZkZjhhOTBjYjA3NGJhMWE4YjZjMzgzM2E5OTEwIiwic3ViIjoiMiIsImF1dGhfdGltZSI6MTQ5NDY2MDc4MywiaWRwIjoibG9jYWwiLCJhbXIiOlsicHdkIl19.AUNbgEoIOdw7_4NB9Hju-npbqWtqbytLe9uPhXuCwJwAbTeSIvHM3hE9ksqUCUIZtR8zYKYrCzUmHvqoZWvOEautxY9sJToPyyFeuuf7eKe5pgaplNFu6M3J8QBN9XRuGhYhipc-Yd3pa1zNmKAPC3yQbo_x139cBWIWHMIOkGxgW7IOcdrNvEB0Dq29tXcrUiOZkeOYC9sP_lLAhWA6_TeVXaJdwQ0vZQRtF7JaQ-Zt2yiFDhu2r3walhtg6AnCMnDVovyz1Vl--j-lANYkuprI-Zyzak-Cps-tT6_JC9sm8OIqVg_aK2t71AWg4dYAfgzYl_3_-N46OiOg8I-p5g&access_token=eyJhbGciOiJSUzI1NiIsImtpZCI6IjkwYWRmOTliMDhmODExMjBiMzdlMWI1NzVmMDliODcwIiwidHlwIjoiSldUIn0.eyJuYmYiOjE0OTQ2NjA3ODQsImV4cCI6MTQ5NDY2MDc5NCwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAxIiwiYXVkIjpbImh0dHA6Ly9sb2NhbGhvc3Q6NTAwMS9yZXNvdXJjZXMiLCJhcGkxIl0sImNsaWVudF9pZCI6Img1Iiwic3ViIjoiMiIsImF1dGhfdGltZSI6MTQ5NDY2MDc4MywiaWRwIjoibG9jYWwiLCJuYW1lIjoiMTIzIiwibmljayI6Iuifi-ifgCIsIm1vYmlsZSI6IjE4NjU4MTMwMzI2Iiwic2NvcGUiOlsib3BlbmlkIiwicHJvZmlsZSIsImFwaTEiXSwiYW1yIjpbInB3ZCJdfQ.lOw-ZLnYt5VejRmh2JnQfL6q2z8T9iLQELUJv4v3vvOkIn5wmUDmhLWkS6GQFXaKwybKCQwlh7OOtb08WZyE-ID7TJS1to7ZqxFR0Q8AGmvsaQxQ2pRTsLcHj11mxdbYhekTxfUldlYYYklupXOCJRe64ioMszpgrwDW1-oepsoUSws9X3yAvwf4rMigZ93-_FMzhfQHBoP2v3vu4x0mRrcas4sX1JIOasBGcTLAttO3HuNHAKrsDZfpxnzhyUZpdmpwGdZEz4pboUIhnh0338BM-WHBCWBzRGtT1CMiqECXhFtbRzNjASlG3jsRXwRSeq7_PvXZmShWHCnkgnYGnw&token_type=Bearer&expires_in=10&scope=openid%20profile%20api1&state=22bdd1faeb21414b8071c915e696fe7a&session_state=lXXBM8MVyOwEPMf_nuzDtafYVsHGmGAJTRfDpGgAmKg.deb0cdd03489a8d0782577e162ceb67f

前端會從 URL 中獲取到 Token 信息,然後把用戶信息和 Token 寫入到上下文中,示例代碼:

new Oidc.UserManager().signinRedirectCallback().then(function () {
    window.location = "/index.html";
}).catch(function (e) {
    console.error(e);
});

可以看到,登錄成功後,是手動設置的跳轉地址,那我們該如何調整到登錄之前的地址呢?其實也很簡單(但我嘗試了好久)就是使用state傳遞地址。

登錄示例代碼:

function login() {
    mgr.signinRedirect({ state: window.location.href });
}

callback.html登錄成功後,回調示例代碼:

new Oidc.UserManager().signinRedirectCallback().then(function (user) {
    window.location = user.state;
}).catch(function (e) {
    console.error(e);
});


IdentityServer4 登錄成功後,跳轉到原來頁面