我遇到了一个问题,我认为我的访问令牌需要一个滑动过期时间。我使用 org.keycloak.adapters.servlet.KeycloakOIDCFilter 在glassfish服务器上运行,以检查所有请求。我设置的过滤器通过确保令牌未过期来检查AccessToken并询问访问权限:
KeycloakSecurityContext kc = (KeycloakSecurityContext) req
.getAttribute(KeycloakSecurityContext.class.getName());
AccessToken token = RSATokenVerifier.create(kc.getIdTokenString()).getToken();
if(token.isExpired()) {
response.redirect("logout url");
}
这很好用。但是,在我的应用程序中,我有一些屏幕,用户可以花费长达一个小时的时间输入信息,以便在完成提供糟糕的用户体验之前将其踢出。还有一些情况是正在进行ajax调用,并且响应被设置为重定向到注销页面,从而导致不良行为。
我真的认为我需要始终检查过期,但我不确定如何在过期时请求新令牌。我感谢任何帮助。谢谢!
答案 0 :(得分:2)
您还需要访问刷新令牌。访问令牌过期后,您几乎无法做到。我将在下面的申请中留下一个例子。
URL url = new URL(keycloakRootURL + "/realms/" + realmName + "/protocol/openid-connect/token");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "Basic " + clientSecret);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
String data = "grant_type=refresh_token&refresh_token=" + refreshToken;
try (OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"))) {
writer.write(data);
writer.flush();
}
conn.connect();
StringBuilder responseStr;
try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
String inputLine;
responseStr = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
responseStr.append(inputLine);
}
}
Object obj = parser.parse(responseStr.toString());
JSONObject result = (JSONObject) obj;
accessCreationTime = System.nanoTime();
return (String) result.get("access_token");
答案 1 :(得分:0)
注销运行良好的keycloak:
public static void keycloakLogout(HttpServletRequest request, HttpSession session) {
SerializableKeycloakAccount keycloakAccount = (SerializableKeycloakAccount) session
.getAttribute(KeycloakAccount.class.getName());
if (keycloakAccount != null && keycloakAccount instanceof SerializableKeycloakAccount) {
RefreshableKeycloakSecurityContext ksc = keycloakAccount.getKeycloakSecurityContext();
KeycloakDeployment deployment = ksc.getDeployment();
// KeycloakDeployment deployment =
// keycloakAccount.getKeycloakSecurityContext().getDeployment();
if (deployment != null) {
ksc.logout(deployment);
// keycloakAccount.getKeycloakSecurityContext().logout(deployment);
request.removeAttribute(KeycloakSecurityContext.class.getName());
session.removeAttribute(TOKEN_KEY);
}
}
}
登录时设置TOKEN_KEY。
<块引用>session.setAttribute(TOKEN_KEY, keycloakToken);