public static List<RoleRepresentation> getRealmRoles(HttpServletRequest req) throws Failure { KeycloakSecurityContext session = (KeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName()); HttpClient client = new HttpClientBuilder().disableTrustManager().build(); try { HttpGet get = new HttpGet( AdapterUtils.getOriginForRestCalls(req.getRequestURL().toString(), session) + "/auth/admin/realms/demo/roles"); get.addHeader("Authorization", "Bearer " + session.getTokenString()); try { HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() != 200) { throw new Failure(response.getStatusLine().getStatusCode()); } HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); try { return JsonSerialization.readValue(is, TypedList.class); } finally { is.close(); } } catch (IOException e) { throw new RuntimeException(e); } } finally { client.getConnectionManager().shutdown(); } }
@Override protected void completeOAuthAuthentication( final KeycloakPrincipal<RefreshableKeycloakSecurityContext> skp) { principal = skp; final RefreshableKeycloakSecurityContext securityContext = skp.getKeycloakSecurityContext(); final Set<String> roles = AdapterUtils.getRolesFromSecurityContext(securityContext); OidcKeycloakAccount account = new OidcKeycloakAccount() { @Override public Principal getPrincipal() { return skp; } @Override public Set<String> getRoles() { return roles; } @Override public KeycloakSecurityContext getKeycloakSecurityContext() { return securityContext; } }; request.setAttribute(KeycloakSecurityContext.class.getName(), securityContext); this.tokenStore.saveAccountInfo(account); }
@Override protected void completeBearerAuthentication( KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal, String method) { this.principal = principal; RefreshableKeycloakSecurityContext securityContext = principal.getKeycloakSecurityContext(); Set<String> roles = AdapterUtils.getRolesFromSecurityContext(securityContext); if (log.isDebugEnabled()) { log.debug("Completing bearer authentication. Bearer roles: " + roles); } request.setAttribute(KeycloakSecurityContext.class.getName(), securityContext); }
protected JsonWebToken createRequestToken(String clientId, String realmInfoUrl) { JsonWebToken reqToken = new JsonWebToken(); reqToken.id(AdapterUtils.generateId()); reqToken.issuer(clientId); reqToken.audience(realmInfoUrl); int now = Time.currentTime(); reqToken.issuedAt(now); reqToken.expiration(now + this.tokenTimeout); reqToken.notBefore(now); return reqToken; }