我正在使用这个插件 https:/github.commauriciovigolokeycloak-angular。 在Angular 7项目中。
版本。
keycloak-angular : 6.1.0
angular : 7.1.4
登录成功后,我得到的回复是这样的。/protocol/openid-connect/token
:
expires_in : 1980
refresh_expires_in : 1800
30分钟后自动注销用户并重定向到登录页面。这种行为很烦人。我希望只要用户还在与应用程序交互,它就会表现得好像什么都没发生一样。换句话说,不要在30分钟后自动注销,应该保持会话活跃。
谁能指导我具体需要哪些步骤来实现这个功能?
编辑1
正如 @thijsfranck 在他的回答中所建议的那样,我修改了这样的代码,并且成功了。
app-init.ts
import {KeycloakService} from 'keycloak-angular';
export function initializer(keycloak: KeycloakService) {
return () => {
return new Promise(async (resolve, reject) => {
try {
const _REALM = "realm";
const _URL = "http://example.com";
const _CLIENT_ID = "id"
await keycloak.init({
config: {
realm: _REALM,
url: _URL,
clientId: _CLIENT_ID,
},
initOptions: {
onLoad: 'login-required',
checkLoginIframe: false
},
enableBearerInterceptor: true,
bearerExcludedUrls: ['/assets', '/clients/public']
})
const keycloakAuth = keycloak.getKeycloakInstance();
const updateToken = async (): Promise < string > => {
const {success,error} = keycloakAuth.updateToken(5);
return new Promise < string > ((res, rej) => {
success(() => res(keycloakAuth.token));
error(rej);
});
}
const login = async (): Promise < void > => {
const {success,error} = keycloakAuth.login();
return new Promise < void > ((res2, rej2) => {
success(res2);
error(rej2);
});
}
keycloakAuth.onTokenExpired = () => {
if (keycloakAuth.refreshToken) {
updateToken();
} else {
login();
}
}
resolve();
} catch (error) {
reject(error);
}
});
};
}
下面是 app.module.ts
providers: [
{
provide: APP_INITIALIZER,
useFactory: initializer,
multi: true,
deps: [KeycloakService]
}
]
当你的认证令牌过期时,你可以使用你的刷新令牌(如果你有一个有效的令牌)来获取一个新的令牌。
请看下面的代码片段。我还没有使用 keycloak-angular
具体而言,但 keycloak-js
(您的库也在使用它)会发出一个叫做 onTokenExpired
当您的认证令牌过期时,您可以使用该事件来触发令牌刷新。您可以使用该事件来触发令牌刷新。如果我没看错的话,您应该可以访问 keycloakAuth
在你 initializer()
职能。
import Keycloak from 'keycloak-js';
private keycloakAuth: Keycloak.KeycloakInstance;
/**
* Whenever the token expires and a refresh token is available, try to refresh the access token.
* Otherwise, redirect to login.
*/
this.keycloakAuth.onTokenExpired = () => {
if (this.keycloakAuth.refreshToken) {
this.updateToken();
} else {
this.login();
}
};
async updateToken(): Promise<string> {
const { success, error } = this.keycloakAuth.updateToken(5);
return new Promise<string>((resolve, reject) => {
success(() => resolve(this.keycloakAuth.token));
error(reject);
});
}
async login(): Promise<void> {
const { success, error } = this.keycloakAuth.login();
return new Promise<void>((resolve, reject) => {
success(resolve);
error(reject);
});
}