protected boolean corsRequest() { if (!deployment.isCors()) return false; KeycloakSecurityContext securityContext = facade.getSecurityContext(); String origin = facade.getRequest().getHeader(CorsHeaders.ORIGIN); String requestOrigin = UriUtils.getOrigin(facade.getRequest().getURI()); log.debugv("Origin: {0} uri: {1}", origin, facade.getRequest().getURI()); if (securityContext != null && origin != null && !origin.equals(requestOrigin)) { AccessToken token = securityContext.getToken(); Set<String> allowedOrigins = token.getAllowedOrigins(); if (log.isDebugEnabled()) { for (String a : allowedOrigins) log.debug(" " + a); } if (allowedOrigins == null || (!allowedOrigins.contains("*") && !allowedOrigins.contains(origin))) { if (allowedOrigins == null) { log.debugv("allowedOrigins was null in token"); } else { log.debugv("allowedOrigins did not contain origin"); } facade.getResponse().setStatus(403); facade.getResponse().end(); return true; } log.debugv("returning origin: {0}", origin); facade.getResponse().setStatus(200); facade.getResponse().setHeader(CorsHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, origin); facade.getResponse().setHeader(CorsHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); } else { log.debugv( "cors validation not needed as we're not a secure session or origin header was null: {0}", facade.getRequest().getURI()); } return false; }
private String loadCustomers(HttpServletRequest req, String refreshToken) throws ServletException, IOException { // Retrieve accessToken first with usage of refresh (offline) token from DB String accessToken = null; try { KeycloakDeployment deployment = getDeployment(req); AccessTokenResponse response = ServerRequest.invokeRefresh(deployment, refreshToken); accessToken = response.getToken(); } catch (ServerRequest.HttpFailure failure) { return "Failed to refresh token. Status from auth-server request: " + failure.getStatus() + ", Error: " + failure.getError(); } // Load customers now HttpGet get = new HttpGet(UriUtils.getOrigin(req.getRequestURL().toString()) + "/database/customers"); get.addHeader("Authorization", "Bearer " + accessToken); HttpResponse response = getHttpClient().execute(get); InputStream is = response.getEntity().getContent(); try { if (response.getStatusLine().getStatusCode() != 200) { return "Error when loading customer. Status: " + response.getStatusLine().getStatusCode() + ", error: " + StreamUtil.readString(is); } else { List<String> list = JsonSerialization.readValue(is, TypedList.class); StringBuilder result = new StringBuilder(); for (String customer : list) { result.append(customer + "<br />"); } return result.toString(); } } finally { is.close(); } }
public void init() { eventStore = session.getProvider(EventStoreProvider.class); account = session .getProvider(AccountProvider.class) .setRealm(realm) .setUriInfo(uriInfo) .setHttpHeaders(headers); AuthenticationManager.AuthResult authResult = authManager.authenticateBearerToken(session, realm, uriInfo, clientConnection, headers); if (authResult != null) { auth = new Auth( realm, authResult.getToken(), authResult.getUser(), client, authResult.getSession(), false); } else { authResult = authManager.authenticateIdentityCookie(session, realm); if (authResult != null) { auth = new Auth( realm, authResult.getToken(), authResult.getUser(), client, authResult.getSession(), true); updateCsrfChecks(); account.setStateChecker(stateChecker); } } String requestOrigin = UriUtils.getOrigin(uriInfo.getBaseUri()); // don't allow cors requests unless they were authenticated by an access token // This is to prevent CSRF attacks. if (auth != null && auth.isCookieAuthenticated()) { String origin = headers.getRequestHeaders().getFirst("Origin"); if (origin != null && !requestOrigin.equals(origin)) { throw new ForbiddenException(); } if (!request.getHttpMethod().equals("GET")) { String referrer = headers.getRequestHeaders().getFirst("Referer"); if (referrer != null && !requestOrigin.equals(UriUtils.getOrigin(referrer))) { throw new ForbiddenException(); } } } if (authResult != null) { UserSessionModel userSession = authResult.getSession(); if (userSession != null) { boolean associated = false; for (ClientSessionModel c : userSession.getClientSessions()) { if (c.getClient().equals(client)) { auth.setClientSession(c); associated = true; break; } } if (!associated) { ClientSessionModel clientSession = session.sessions().createClientSession(realm, client); clientSession.setUserSession(userSession); auth.setClientSession(clientSession); } } account.setUser(auth.getUser()); } boolean eventsEnabled = eventStore != null && realm.isEventsEnabled(); // todo find out from federation if password is updatable account.setFeatures(realm.isIdentityFederationEnabled(), eventsEnabled, true); }