Java Code Examples for org.keycloak.common.util.KeycloakUriBuilder#fromUri()

The following examples show how to use org.keycloak.common.util.KeycloakUriBuilder#fromUri() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CASLoginProtocol.java    From keycloak-protocol-cas with Apache License 2.0 6 votes vote down vote up
@Override
public Response authenticated(AuthenticationSessionModel authSession, UserSessionModel userSession, ClientSessionContext clientSessionCtx) {
    AuthenticatedClientSessionModel clientSession = clientSessionCtx.getClientSession();

    String service = authSession.getRedirectUri();
    //TODO validate service

    OAuth2Code codeData = new OAuth2Code(UUID.randomUUID(),
            Time.currentTime() + userSession.getRealm().getAccessCodeLifespan(),
            null, null, authSession.getRedirectUri(), null, null);
    String code = OAuth2CodeParser.persistCode(session, clientSession, codeData);

    KeycloakUriBuilder uriBuilder = KeycloakUriBuilder.fromUri(service);
    uriBuilder.queryParam(TICKET_RESPONSE_PARAM, SERVICE_TICKET_PREFIX + code);

    URI redirectUri = uriBuilder.build();

    Response.ResponseBuilder location = Response.status(302).location(redirectUri);
    return location.build();
}
 
Example 2
Source File: ResourceAdminManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private List<String> getAllManagementUrls(ClientModel client) {
    String baseMgmtUrl = getManagementUrl(session, client);
    if (baseMgmtUrl == null) {
        return Collections.emptyList();
    }

    Set<String> registeredNodesHosts = new ClientManager().validateRegisteredNodes(client);

    // No-cluster setup
    if (registeredNodesHosts.isEmpty()) {
        return Arrays.asList(baseMgmtUrl);
    }

    List<String> result = new LinkedList<String>();
    KeycloakUriBuilder uriBuilder = KeycloakUriBuilder.fromUri(baseMgmtUrl);
    for (String nodeHost : registeredNodesHosts) {
        String currentNodeUri = uriBuilder.clone().host(nodeHost).build().toString();
        result.add(currentNodeUri);
    }

    return result;
}
 
Example 3
Source File: AdapterDeploymentContext.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected KeycloakUriBuilder getBaseBuilder(HttpFacade facade, String base) {
    KeycloakUriBuilder builder = KeycloakUriBuilder.fromUri(base);
    URI request = URI.create(facade.getRequest().getURI());
    String scheme = request.getScheme();
    if (deployment.getSslRequired().isRequired(facade.getRequest().getRemoteAddr())) {
        scheme = "https";
        if (!request.getScheme().equals(scheme) && request.getPort() != -1) {
            log.error("request scheme: " + request.getScheme() + " ssl required");
            throw new RuntimeException("Can't resolve relative url from adapter config.");
        }
    }
    builder.scheme(scheme);
    builder.host(request.getHost());
    if (request.getPort() != -1) {
       builder.port(request.getPort());
    }
    return builder;
}
 
Example 4
Source File: KeycloakDeployment.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void resolveUrls(KeycloakUriBuilder authUrlBuilder) {
    if (log.isDebugEnabled()) {
        log.debug("resolveUrls");
    }

    String login = authUrlBuilder.clone().path(ServiceUrlConstants.AUTH_PATH).build(getRealm()).toString();
    authUrl = KeycloakUriBuilder.fromUri(login);
    realmInfoUrl = authUrlBuilder.clone().path(ServiceUrlConstants.REALM_INFO_PATH).build(getRealm()).toString();

    tokenUrl = authUrlBuilder.clone().path(ServiceUrlConstants.TOKEN_PATH).build(getRealm()).toString();
    logoutUrl = KeycloakUriBuilder.fromUri(authUrlBuilder.clone().path(ServiceUrlConstants.TOKEN_SERVICE_LOGOUT_PATH).build(getRealm()).toString());
    accountUrl = authUrlBuilder.clone().path(ServiceUrlConstants.ACCOUNT_SERVICE_PATH).build(getRealm()).toString();
    registerNodeUrl = authUrlBuilder.clone().path(ServiceUrlConstants.CLIENTS_MANAGEMENT_REGISTER_NODE_PATH).build(getRealm()).toString();
    unregisterNodeUrl = authUrlBuilder.clone().path(ServiceUrlConstants.CLIENTS_MANAGEMENT_UNREGISTER_NODE_PATH).build(getRealm()).toString();
    jwksUrl = authUrlBuilder.clone().path(ServiceUrlConstants.JWKS_URL).build(getRealm()).toString();
}
 
Example 5
Source File: ContainerInfo.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public KeycloakUriBuilder getUriBuilder() {
    try {
        return KeycloakUriBuilder.fromUri(getContextRoot().toURI());
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}
 
Example 6
Source File: ResourcesRestServiceTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private List<AbstractResourceService.ResourcePermission> getSharedWithMe(String userName, String name, int first, int max, Consumer<SimpleHttp.Response> responseHandler) {
    KeycloakUriBuilder uri = KeycloakUriBuilder.fromUri("/shared-with-me");

    if (name != null) {
        uri.queryParam("name", name);
    }

    if (first > -1 && max > -1) {
        uri.queryParam("first", first);
        uri.queryParam("max", max);
    }

    return doGet(uri.build().toString(), authzClient.obtainAccessToken(userName, "password").getToken(),
            new TypeReference<List<AbstractResourceService.ResourcePermission>>() {}, responseHandler);
}
 
Example 7
Source File: ResourcesRestServiceTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private List<Resource> getMyResources(String name, int first, int max) {
    KeycloakUriBuilder uri = KeycloakUriBuilder.fromUri("");

    if (name != null) {
        uri.queryParam("name", name);
    }

    if (first > -1 && max > -1) {
        uri.queryParam("first", first);
        uri.queryParam("max", max);
    }

    return doGet(uri.build().toString(), new TypeReference<List<Resource>>() {});
}
 
Example 8
Source File: OIDCRedirectUriBuilder.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static OIDCRedirectUriBuilder fromUri(String baseUri, OIDCResponseMode responseMode) {
    KeycloakUriBuilder uriBuilder = KeycloakUriBuilder.fromUri(baseUri);

    switch (responseMode) {
        case QUERY: return new QueryRedirectUriBuilder(uriBuilder);
        case FRAGMENT: return new FragmentRedirectUriBuilder(uriBuilder);
        case FORM_POST: return new FormPostRedirectUriBuilder(uriBuilder);
    }

    throw new IllegalStateException("Not possible to end here");
}
 
Example 9
Source File: KeycloakDeployment.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * URLs are loaded lazily when used. This allows adapter to be deployed prior to Keycloak server starting, and will
 * also allow the adapter to retry loading config for each request until the Keycloak server is ready.
 *
 * In the future we may want to support reloading config at a configurable interval.
 */
protected void resolveUrls() {
    if (realmInfoUrl == null) {
        synchronized (this) {
            KeycloakUriBuilder authUrlBuilder = KeycloakUriBuilder.fromUri(authServerBaseUrl);

            String discoveryUrl = authUrlBuilder.clone().path(ServiceUrlConstants.DISCOVERY_URL).build(getRealm()).toString();
            try {
                log.debugv("Resolving URLs from {0}", discoveryUrl);

                OIDCConfigurationRepresentation config = getOidcConfiguration(discoveryUrl);

                authUrl = KeycloakUriBuilder.fromUri(config.getAuthorizationEndpoint());
                realmInfoUrl = config.getIssuer();

                tokenUrl = config.getTokenEndpoint();
                logoutUrl = KeycloakUriBuilder.fromUri(config.getLogoutEndpoint());
                accountUrl = KeycloakUriBuilder.fromUri(config.getIssuer()).path("/account").build().toString();
                registerNodeUrl = authUrlBuilder.clone().path(ServiceUrlConstants.CLIENTS_MANAGEMENT_REGISTER_NODE_PATH).build(getRealm()).toString();
                unregisterNodeUrl = authUrlBuilder.clone().path(ServiceUrlConstants.CLIENTS_MANAGEMENT_UNREGISTER_NODE_PATH).build(getRealm()).toString();
                jwksUrl = config.getJwksUri();

                log.infov("Loaded URLs from {0}", discoveryUrl);
            } catch (Exception e) {
                log.warnv(e, "Failed to load URLs from {0}", discoveryUrl);
            }
        }
    }
}
 
Example 10
Source File: BaseSAML2BindingBuilder.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public URI generateRedirectUri(String samlParameterName, String redirectUri, Document document) throws ConfigurationException, ProcessingException, IOException {
    KeycloakUriBuilder builder = KeycloakUriBuilder.fromUri(redirectUri);
    int pos = builder.getQuery() == null? 0 : builder.getQuery().length();
    builder.queryParam(samlParameterName, base64Encoded(document));
    if (relayState != null) {
        builder.queryParam("RelayState", relayState);
    }

    if (sign) {
        builder.queryParam(GeneralConstants.SAML_SIG_ALG_REQUEST_KEY, signatureAlgorithm.getXmlSignatureMethod());
        URI uri = builder.build();
        String rawQuery = uri.getRawQuery();
        if (pos > 0) {
            // just set in the signature the added SAML parameters
            rawQuery = rawQuery.substring(pos + 1);
        }
        Signature signature = signatureAlgorithm.createSignature();
        byte[] sig = new byte[0];
        try {
            signature.initSign(signingKeyPair.getPrivate());
            signature.update(rawQuery.getBytes(GeneralConstants.SAML_CHARSET));
            sig = signature.sign();
        } catch (InvalidKeyException | SignatureException e) {
            throw new ProcessingException(e);
        }
        String encodedSig = RedirectBindingUtil.base64Encode(sig);
        builder.queryParam(GeneralConstants.SAML_SIGNATURE_REQUEST_KEY, encodedSig);
    }
    return builder.build();
}
 
Example 11
Source File: AbstractSecuredLocalService.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Path("login-redirect")
@GET
public Response loginRedirect(@QueryParam("code") String code,
                              @QueryParam("state") String state,
                              @QueryParam("error") String error,
                              @QueryParam("path") String path,
                              @QueryParam("referrer") String referrer,
                              @Context HttpHeaders headers) {
    try {
        if (error != null) {
            if (OAuthErrorException.ACCESS_DENIED.equals(error)) {
                // cased by CANCELLED_BY_USER or CONSENT_DENIED
                session.getContext().setClient(client);
                return session.getProvider(LoginFormsProvider.class).setError(Messages.NO_ACCESS).createErrorPage(Response.Status.FORBIDDEN);
            } else {
                logger.debug("error from oauth");
                throw new ForbiddenException("error");
            }
        }
        if (path != null && !getValidPaths().contains(path)) {
            throw new BadRequestException("Invalid path");
        }
        if (!realm.isEnabled()) {
            logger.debug("realm not enabled");
            throw new ForbiddenException();
        }
        if (!client.isEnabled()) {
            logger.debug("account management app not enabled");
            throw new ForbiddenException();
        }
        if (code == null) {
            logger.debug("code not specified");
            throw new BadRequestException("code not specified");
        }
        if (state == null) {
            logger.debug("state not specified");
            throw new BadRequestException("state not specified");
        }
        KeycloakUriBuilder redirect = KeycloakUriBuilder.fromUri(getBaseRedirectUri());
        if (path != null) {
            redirect.path(path);
        }
        if (referrer != null) {
            redirect.queryParam("referrer", referrer);
        }

        return Response.status(302).location(redirect.build()).build();
    } finally {
    }
}
 
Example 12
Source File: AdapterDeploymentContext.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public void setAuthServerBaseUrl(String authServerBaseUrl) {
    this.authServerBaseUrl = authServerBaseUrl;
    KeycloakUriBuilder serverBuilder = KeycloakUriBuilder.fromUri(authServerBaseUrl);
    resolveUrls(serverBuilder);
}