use of org.keycloak.adapters.KeycloakDeployment in project keycloak by keycloak.
the class KeycloakAuthenticationProcessingFilter method attemptAuthentication.
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
log.debug("Attempting Keycloak authentication");
HttpFacade facade = new SimpleHttpFacade(request, response);
KeycloakDeployment deployment = adapterDeploymentContext.resolveDeployment(facade);
// using Spring authenticationFailureHandler
deployment.setDelegateBearerErrorResponseSending(true);
AdapterTokenStore tokenStore = adapterTokenStoreFactory.createAdapterTokenStore(deployment, request, response);
RequestAuthenticator authenticator = requestAuthenticatorFactory.createRequestAuthenticator(facade, request, deployment, tokenStore, -1);
AuthOutcome result = authenticator.authenticate();
log.debug("Auth outcome: {}", result);
if (AuthOutcome.FAILED.equals(result)) {
AuthChallenge challenge = authenticator.getChallenge();
if (challenge != null) {
challenge.challenge(facade);
}
throw new KeycloakAuthenticationException("Invalid authorization header, see WWW-Authenticate header for details");
}
if (AuthOutcome.NOT_ATTEMPTED.equals(result)) {
AuthChallenge challenge = authenticator.getChallenge();
if (challenge != null) {
challenge.challenge(facade);
}
if (deployment.isBearerOnly()) {
// no redirection in this mode, throwing exception for the spring handler
throw new KeycloakAuthenticationException("Authorization header not found, see WWW-Authenticate header");
} else {
// let continue if challenged, it may redirect
return null;
}
} else if (AuthOutcome.AUTHENTICATED.equals(result)) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Assert.notNull(authentication, "Authentication SecurityContextHolder was null");
return authenticationManager.authenticate(authentication);
} else {
AuthChallenge challenge = authenticator.getChallenge();
if (challenge != null) {
challenge.challenge(facade);
}
return null;
}
}
use of org.keycloak.adapters.KeycloakDeployment in project keycloak by keycloak.
the class AdapterDeploymentContextFactoryBean method afterPropertiesSet.
@Override
public void afterPropertiesSet() throws Exception {
if (keycloakConfigResolver != null) {
adapterDeploymentContext = new AdapterDeploymentContext(keycloakConfigResolver);
} else {
log.info("Loading Keycloak deployment from configuration file: {}", keycloakConfigFileResource);
KeycloakDeployment deployment = loadKeycloakDeployment();
adapterDeploymentContext = new AdapterDeploymentContext(deployment);
}
}
use of org.keycloak.adapters.KeycloakDeployment in project openremote by openremote.
the class KeycloakIdentityProvider method init.
@Override
public void init(Container container) {
if (httpClient != null) {
return;
}
sessionMaxSeconds = getInteger(container.getConfig(), IDENTITY_SESSION_MAX_MINUTES, IDENTITY_SESSION_MAX_MINUTES_DEFAULT) * 60;
if (sessionMaxSeconds < 60) {
throw new IllegalArgumentException(IDENTITY_SESSION_MAX_MINUTES + " must be more than 1 minute");
}
// Use the same, as a session is never idle because we periodically check if the refresh token is
// still good in frontend code, this check will reset the idle timeout anyway
sessionTimeoutSeconds = sessionMaxSeconds;
sessionOfflineTimeoutSeconds = getInteger(container.getConfig(), IDENTITY_SESSION_OFFLINE_TIMEOUT_MINUTES, IDENTITY_SESSION_OFFLINE_TIMEOUT_MINUTES_DEFAULT) * 60;
if (sessionOfflineTimeoutSeconds < 60) {
throw new IllegalArgumentException(IDENTITY_SESSION_OFFLINE_TIMEOUT_MINUTES + " must be more than 1 minute");
}
keycloakServiceUri = UriBuilder.fromPath("/").scheme("http").host(getString(container.getConfig(), KEYCLOAK_HOST, KEYCLOAK_HOST_DEFAULT)).port(getInteger(container.getConfig(), KEYCLOAK_PORT, KEYCLOAK_PORT_DEFAULT)).path(KEYCLOAK_AUTH_PATH);
LOG.info("Keycloak service URL: " + keycloakServiceUri.build());
ResteasyClientBuilder clientBuilder = new ResteasyClientBuilder().connectTimeout(getInteger(container.getConfig(), KEYCLOAK_CONNECT_TIMEOUT, KEYCLOAK_CONNECT_TIMEOUT_DEFAULT), TimeUnit.MILLISECONDS).readTimeout(getInteger(container.getConfig(), KEYCLOAK_REQUEST_TIMEOUT, KEYCLOAK_REQUEST_TIMEOUT_DEFAULT), TimeUnit.MILLISECONDS).connectionPoolSize(getInteger(container.getConfig(), KEYCLOAK_CLIENT_POOL_SIZE, KEYCLOAK_CLIENT_POOL_SIZE_DEFAULT));
httpClient = WebClient.registerDefaults(clientBuilder).build();
setActiveCredentials(getDefaultKeycloakGrant(container));
keycloakDeploymentCache = createKeycloakDeploymentCache();
keycloakConfigResolver = request -> {
// The realm we authenticate against must be available as a request header
String realm = request.getHeader(REALM_PARAM_NAME);
if (realm == null || realm.length() == 0) {
LOG.finer("No realm in request, no authentication will be attempted: " + request.getURI());
return notAuthenticatedKeycloakDeployment;
}
KeycloakDeployment keycloakDeployment = getKeycloakDeployment(realm, KEYCLOAK_CLIENT_ID);
if (keycloakDeployment == null) {
LOG.fine("No Keycloak deployment available for realm, no authentication will be attempted: " + request.getURI());
return notAuthenticatedKeycloakDeployment;
}
return keycloakDeployment;
};
if (container.isDevMode()) {
authProxyHandler = ProxyHandler.builder().setProxyClient(new LoadBalancingProxyClient().addHost(keycloakServiceUri.clone().replacePath("").build())).setMaxRequestTime(getInteger(container.getConfig(), KEYCLOAK_REQUEST_TIMEOUT, KEYCLOAK_REQUEST_TIMEOUT_DEFAULT)).setNext(ResponseCodeHandler.HANDLE_404).setReuseXForwarded(true).build();
}
// TODO Not a great way to block startup while we wait for other services (Hystrix?)
waitForKeycloak();
LOG.info("Keycloak identity provider available: " + keycloakServiceUri.build());
}
use of org.keycloak.adapters.KeycloakDeployment in project openremote by openremote.
the class KeycloakIdentityProvider method createKeycloakDeploymentCache.
protected LoadingCache<KeycloakRealmClient, KeycloakDeployment> createKeycloakDeploymentCache() {
CacheLoader<KeycloakRealmClient, KeycloakDeployment> loader = new CacheLoader<KeycloakRealmClient, KeycloakDeployment>() {
public KeycloakDeployment load(KeycloakRealmClient keycloakRealmClient) {
LOG.fine("Loading adapter config for client '" + keycloakRealmClient.clientId + "' in realm '" + keycloakRealmClient.realm + "'");
// KeycloakResource keycloak = getKeycloak();
KeycloakResource keycloak = getTarget(httpClient, keycloakServiceUri.build(), null, null, null).proxy(KeycloakResource.class);
// Can't get adapter for client in another realm
AdapterConfig adapterConfig = keycloak.getAdapterConfig(// keycloakRealmClient.clientId
keycloakRealmClient.realm, // keycloakRealmClient.clientId
KEYCLOAK_CLIENT_ID);
// The auth-server-url in the adapter config must be reachable by this manager it will be the frontend URL by default
adapterConfig.setAuthServerUrl(keycloakServiceUri.clone().build().toString());
return KeycloakDeploymentBuilder.build(adapterConfig);
}
};
// TODO configurable? Or replace all of this with Observable.cache()?
return CacheBuilder.newBuilder().maximumSize(500).expireAfterWrite(10, MINUTES).build(loader);
}
use of org.keycloak.adapters.KeycloakDeployment in project keycloak by keycloak.
the class KeycloakAdapterPolicyEnforcer method requestAuthorizationToken.
private AccessToken requestAuthorizationToken(PathConfig pathConfig, PolicyEnforcerConfig.MethodConfig methodConfig, OIDCHttpFacade httpFacade, Map<String, List<String>> claims) {
if (getEnforcerConfig().getUserManagedAccess() != null) {
return null;
}
try {
KeycloakSecurityContext securityContext = httpFacade.getSecurityContext();
String accessTokenString = securityContext.getTokenString();
KeycloakDeployment deployment = getPolicyEnforcer().getDeployment();
AccessToken accessToken = securityContext.getToken();
AuthorizationRequest authzRequest = new AuthorizationRequest();
if (isBearerAuthorization(httpFacade) || accessToken.getAuthorization() != null) {
authzRequest.addPermission(pathConfig.getId(), methodConfig.getScopes());
}
if (!claims.isEmpty()) {
authzRequest.setClaimTokenFormat("urn:ietf:params:oauth:token-type:jwt");
authzRequest.setClaimToken(Base64.encodeBytes(JsonSerialization.writeValueAsBytes(claims)));
}
if (accessToken.getAuthorization() != null) {
authzRequest.setRpt(accessTokenString);
}
LOGGER.debug("Obtaining authorization for authenticated user.");
AuthorizationResponse authzResponse;
if (isBearerAuthorization(httpFacade)) {
authzRequest.setSubjectToken(accessTokenString);
authzResponse = getAuthzClient().authorization().authorize(authzRequest);
} else {
authzResponse = getAuthzClient().authorization(accessTokenString).authorize(authzRequest);
}
if (authzResponse != null) {
return AdapterTokenVerifier.verifyToken(authzResponse.getToken(), deployment);
}
} catch (AuthorizationDeniedException ignore) {
LOGGER.debug("Authorization denied", ignore);
} catch (Exception e) {
LOGGER.debug("Authorization failed", e);
}
return null;
}
Aggregations