org.keycloak.common.util.KeycloakUriBuilder Java Examples

The following examples show how to use org.keycloak.common.util.KeycloakUriBuilder. 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: CarsAppController.java    From devconf2019-authz with Apache License 2.0 7 votes vote down vote up
@RequestMapping(value = "/app", method = RequestMethod.GET)
public String showCarsPage(Principal principal, Model model) {
    boolean isCreateCarAllowed = carsClientService.isCreateCarAllowed(principal);
    model.addAttribute("create_car_allowed", isCreateCarAllowed);

    Map<String, List<CarRepresentation>> cars = carsClientService.getCars();
    model.addAttribute("cars", cars);
    model.addAttribute("principal",  principal);

    String logoutUri = KeycloakUriBuilder.fromUri(appConfig.getAuthServerUrl()).path(ServiceUrlConstants.TOKEN_SERVICE_LOGOUT_PATH)
            .queryParam("redirect_uri", "http://localhost:8080/app").build(appConfig.getRealmName()).toString();
    model.addAttribute("logout",  logoutUri);

    String accountUri = KeycloakUriBuilder.fromUri(appConfig.getAuthServerUrl()).path(ServiceUrlConstants.ACCOUNT_SERVICE_PATH)
            .queryParam("referrer", appConfig.getClientId()).build(appConfig.getRealmName()).toString();
    model.addAttribute("accountUri", accountUri);

    AccessToken token = AppTokenUtil.getAccessToken(principal);
    model.addAttribute("token", token);

    return "cars";
}
 
Example #2
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 #3
Source File: ElytronSamlSessionStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public String getRedirectUri() {
    HttpScope session = exchange.getScope(Scope.SESSION);
    String redirect = (String) session.getAttachment(SAML_REDIRECT_URI);
    if (redirect == null) {
        URI uri = exchange.getURI();
        String path = uri.getPath();
        String relativePath = exchange.getRequest().getRelativePath();
        String contextPath = path.substring(0, path.indexOf(relativePath));

        if (!contextPath.isEmpty()) {
            contextPath = contextPath + "/";
        }

        String baseUri = KeycloakUriBuilder.fromUri(path).replacePath(contextPath).build().toString();
        return SamlUtil.getRedirectTo(exchange, contextPath, baseUri);
    }
    return redirect;
}
 
Example #4
Source File: KeycloakInstalled.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected String createAuthUrl(String redirectUri, String state, Pkce pkce) {

        KeycloakUriBuilder builder = deployment.getAuthUrl().clone()
                .queryParam(OAuth2Constants.RESPONSE_TYPE, OAuth2Constants.CODE)
                .queryParam(OAuth2Constants.CLIENT_ID, deployment.getResourceName())
                .queryParam(OAuth2Constants.REDIRECT_URI, redirectUri)
                .queryParam(OAuth2Constants.SCOPE, OAuth2Constants.SCOPE_OPENID);

        if (state != null) {
            builder.queryParam(OAuth2Constants.STATE, state);
        }

        if (locale != null) {
            builder.queryParam(OAuth2Constants.UI_LOCALES_PARAM, locale.getLanguage());
        }

        if (pkce != null) {
            builder.queryParam(OAuth2Constants.CODE_CHALLENGE, pkce.getCodeChallenge());
            builder.queryParam(OAuth2Constants.CODE_CHALLENGE_METHOD, "S256");
        }

        return builder.build().toString();
    }
 
Example #5
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 #6
Source File: KeycloakDeployment.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public void setAuthServerBaseUrl(AdapterConfig config) {
    this.authServerBaseUrl = config.getAuthServerUrl();
    if (authServerBaseUrl == null) return;

    authServerBaseUrl = KeycloakUriBuilder.fromUri(authServerBaseUrl).build().toString();

    authUrl = null;
    realmInfoUrl = null;
    tokenUrl = null;
    logoutUrl = null;
    accountUrl = null;
    registerNodeUrl = null;
    unregisterNodeUrl = null;
    jwksUrl = null;

    URI authServerUri = URI.create(authServerBaseUrl);

    if (authServerUri.getHost() == null) {
        relativeUrls = RelativeUrlsUsed.ALWAYS;
    } else {
        // We have absolute URI in config
        relativeUrls = RelativeUrlsUsed.NEVER;
    }
}
 
Example #7
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 #8
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 #9
Source File: ResourcesService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private Link[] createPageLinks(Integer first, Integer max, int resultSize) {
    if (resultSize == 0 || (first == 0 && resultSize <= max)) {
        return new Link[] {};
    }

    List<Link> links = new ArrayList();
    boolean nextPage = resultSize > max;

    if (nextPage) {
        links.add(Link.fromUri(
                KeycloakUriBuilder.fromUri(uriInfo.getRequestUri()).replaceQuery("first={first}&max={max}")
                        .build(first + max, max))
                .rel("next").build());
    }

    if (first > 0) {
        links.add(Link.fromUri(
                KeycloakUriBuilder.fromUri(uriInfo.getRequestUri()).replaceQuery("first={first}&max={max}")
                        .build(Math.max(first - max, 0), max))
                .rel("prev").build());
    }

    return links.toArray(new Link[links.size()]);
}
 
Example #10
Source File: AuthzClient.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private AuthzClient(Configuration configuration, ClientAuthenticator authenticator) {
    if (configuration == null) {
        throw new IllegalArgumentException("Client configuration can not be null.");
    }

    String configurationUrl = configuration.getAuthServerUrl();

    if (configurationUrl == null) {
        throw new IllegalArgumentException("Configuration URL can not be null.");
    }

    configurationUrl = KeycloakUriBuilder.fromUri(configurationUrl).clone().path(AUTHZ_DISCOVERY_URL).build(configuration.getRealm()).toString(); 
    this.configuration = configuration;

    this.http = new Http(configuration, authenticator != null ? authenticator : configuration.getClientAuthenticator());

    try {
        this.serverConfiguration = this.http.<ServerConfiguration>get(configurationUrl)
                .response().json(ServerConfiguration.class)
                .execute();
    } catch (Exception e) {
        throw new RuntimeException("Could not obtain configuration from server [" + configurationUrl + "].", e);
    }

    this.http.setServerConfiguration(this.serverConfiguration);
}
 
Example #11
Source File: AbstractIdentityProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected String getLinkingUrl(UriInfo uriInfo, ClientModel authorizedClient, UserSessionModel tokenUserSession) {
    String provider = getConfig().getAlias();
    String clientId = authorizedClient.getClientId();
    String nonce = UUID.randomUUID().toString();
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    String input = nonce + tokenUserSession.getId() + clientId + provider;
    byte[] check = md.digest(input.getBytes(StandardCharsets.UTF_8));
    String hash = Base64Url.encode(check);
    return KeycloakUriBuilder.fromUri(uriInfo.getBaseUri())
            .path("/realms/{realm}/broker/{provider}/link")
            .queryParam("nonce", nonce)
            .queryParam("hash", hash)
            .queryParam("client_id", clientId)
            .build(authorizedClient.getRealm().getName(), provider)
            .toString();
}
 
Example #12
Source File: KeycloakAdminClient.java    From nexus3-keycloak-plugin with Apache License 2.0 6 votes vote down vote up
public AccessTokenResponse obtainAccessToken(String username, String password) {
    URI uri = KeycloakUriBuilder.fromUri(this.config.getAuthServerUrl())
                                .path(ServiceUrlConstants.TOKEN_PATH)
                                .build(this.config.getRealm());
    HttpMethod<AccessTokenResponse> httpMethod = getHttp().post(uri);

    httpMethod = httpMethod.form()
                           .param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD)
                           .param("username", username)
                           .param("password", password);

    if (this.config.isPublicClient()) {
        httpMethod.param(OAuth2Constants.CLIENT_ID, this.config.getResource());
    } else {
        httpMethod.authorizationBasic(this.config.getResource(),
                                      this.config.getCredentials().get("secret").toString());
    }

    return httpMethod.response().json(AccessTokenResponse.class).execute();
}
 
Example #13
Source File: KeycloakAuthenticationProcessingFilterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testAttemptAuthenticationExpectRedirect() throws Exception {
    when(keycloakDeployment.getAuthUrl()).thenReturn(KeycloakUriBuilder.fromUri("http://localhost:8080/auth"));
    when(keycloakDeployment.getResourceName()).thenReturn("resource-name");
    when(keycloakDeployment.getStateCookieName()).thenReturn("kc-cookie");
    when(keycloakDeployment.getSslRequired()).thenReturn(SslRequired.NONE);
    when(keycloakDeployment.isBearerOnly()).thenReturn(Boolean.FALSE);

    filter.attemptAuthentication(request, response);
    verify(response).setStatus(302);
    verify(response).setHeader(eq("Location"), startsWith("http://localhost:8080/auth"));
}
 
Example #14
Source File: AdminClient.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void logout(HttpServletRequest request, AccessTokenResponse res) throws IOException {

        HttpClient client = new DefaultHttpClient();


        try {
            HttpPost post = new HttpPost(KeycloakUriBuilder.fromUri(UriUtils.getOrigin(request.getRequestURL().toString()) + "/auth")
                    .path(ServiceUrlConstants.TOKEN_SERVICE_LOGOUT_PATH)
                    .build("demo"));
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            formparams.add(new BasicNameValuePair(OAuth2Constants.REFRESH_TOKEN, res.getRefreshToken()));
            formparams.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ID, "admin-client"));
            UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8");
            post.setEntity(form);
            HttpResponse response = client.execute(post);
            boolean status = response.getStatusLine().getStatusCode() != 204;
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            InputStream is = entity.getContent();
            if (is != null) is.close();
            if (status) {
                throw new RuntimeException("failed to logout");
            }
        } finally {
            client.getConnectionManager().shutdown();
        }
    }
 
Example #15
Source File: CookieTokenStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
static String getContextPath(HttpFacade facade) {
    String uri = facade.getRequest().getURI();
    String path = KeycloakUriBuilder.fromUri(uri).getPath();
    if (path == null || path.isEmpty()) {
        return "/";
    }
    int index = path.indexOf("/", 1);
    return index == -1 ? path : path.substring(0, index);
}
 
Example #16
Source File: BasicAuthRequestAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected AccessTokenResponse getToken(String username, String password) throws Exception {
	AccessTokenResponse tokenResponse=null;
	HttpClient client = deployment.getClient();

    HttpPost post = new HttpPost(
            KeycloakUriBuilder.fromUri(deployment.getAuthServerBaseUrl())
            .path(ServiceUrlConstants.TOKEN_PATH).build(deployment.getRealm()));
    java.util.List <NameValuePair> formparams = new java.util.ArrayList <NameValuePair>();
    formparams.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD));
    formparams.add(new BasicNameValuePair("username", username));
    formparams.add(new BasicNameValuePair("password", password));

    ClientCredentialsProviderUtils.setClientCredentials(deployment, post, formparams);

    UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8");
    post.setEntity(form);

    HttpResponse response = client.execute(post);
    int status = response.getStatusLine().getStatusCode();
    HttpEntity entity = response.getEntity();
    if (status != 200) {
        EntityUtils.consumeQuietly(entity);
        throw new java.io.IOException("Bad status: " + status);
    }
    if (entity == null) {
        throw new java.io.IOException("No Entity");
    }
    java.io.InputStream is = entity.getContent();
    try {
        tokenResponse = JsonSerialization.readValue(is, AccessTokenResponse.class);
    } finally {
        try {
            is.close();
        } catch (java.io.IOException ignored) { }
    }
	
	return (tokenResponse);
}
 
Example #17
Source File: OAuthRequestAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * strip out unwanted query parameters and redirect so bookmarks don't retain oauth protocol bits
 */
protected String stripOauthParametersFromRedirect() {
    KeycloakUriBuilder builder = KeycloakUriBuilder.fromUri(facade.getRequest().getURI())
            .replaceQueryParam(OAuth2Constants.CODE, null)
            .replaceQueryParam(OAuth2Constants.STATE, null)
            .replaceQueryParam(OAuth2Constants.SESSION_STATE, null);
    return builder.build().toString();
}
 
Example #18
Source File: KeycloakLinkedAccountsProvider.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
/**
 * @see io.apicurio.hub.api.security.ILinkedAccountsProvider#getLinkedAccountToken(io.apicurio.hub.core.beans.LinkedAccountType)
 */
@Override
public String getLinkedAccountToken(LinkedAccountType type) throws IOException {
    String authServerRootUrl = config.getKeycloakAuthUrl();
    String realm = config.getKeycloakRealm();
    String provider = type.alias();

    try {
        String externalTokenUrl = KeycloakUriBuilder.fromUri(authServerRootUrl)
                .path("/realms/{realm}/broker/{provider}/token")
                .build(realm, provider).toString();
        String token = this.security.getToken();

        HttpGet get = new HttpGet(externalTokenUrl);
        get.addHeader("Accept", "application/json");
        get.addHeader("Authorization", "Bearer " + token);

        try (CloseableHttpResponse response = httpClient.execute(get)) {
            if (response.getStatusLine().getStatusCode() != 200) {
                logger.error("Failed to access External IDP Access Token from Keycloak: {} - {}", 
                        response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
                throw new IOException(
                        "Unexpected response from Keycloak: " + response.getStatusLine().getStatusCode() + "::"
                                + response.getStatusLine().getReasonPhrase());
            }
            
            try (InputStream contentStream = response.getEntity().getContent()) {
                String content = IOUtils.toString(contentStream, Charset.forName("UTF-8"));
                return content;
            }
        }            
    } catch (IllegalArgumentException e) {
        throw new IOException("Error getting linked account token.", e);
    }
}
 
Example #19
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 #20
Source File: KeycloakLinkedAccountsProvider.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
/**
 * @see io.apicurio.hub.api.security.ILinkedAccountsProvider#deleteLinkedAccount(io.apicurio.hub.core.beans.LinkedAccountType)
 */
@Override
public void deleteLinkedAccount(LinkedAccountType type) throws IOException {
    try {
        KeycloakSecurityContext session = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());

        String authServerRootUrl = config.getKeycloakAuthUrl();
        String realm = config.getKeycloakRealm();
        String provider = type.alias();

        session.getToken().getSessionState();

        String url = KeycloakUriBuilder.fromUri(authServerRootUrl)
            .path("/realms/{realm}/account/federated-identity-update")
            .queryParam("action", "REMOVE").queryParam("provider_id", provider).build(realm)
            .toString();
        logger.debug("Deleting identity provider using URL: {}", url);

        HttpGet get = new HttpGet(url);
        get.addHeader("Accept", "application/json");
        get.addHeader("Authorization", "Bearer " + session.getTokenString());
        
        try (CloseableHttpResponse response = httpClient.execute(get)) {
            if (response.getStatusLine().getStatusCode() != 200) {
                logger.debug("HTTP Response Status Code when deleting identity provider: {}",
                    response.getStatusLine().getStatusCode());
            }
        }            
    } catch (Exception e) {
        throw new IOException("Error deleting linked account.", e);
    }
}
 
Example #21
Source File: KeycloakDeploymentTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected OIDCConfigurationRepresentation getOidcConfiguration(String discoveryUrl) throws Exception {
    String base = KeycloakUriBuilder.fromUri(discoveryUrl).replacePath("/auth").build().toString();

    OIDCConfigurationRepresentation rep = new OIDCConfigurationRepresentation();
    rep.setAuthorizationEndpoint(base + "/realms/test/authz");
    rep.setTokenEndpoint(base + "/realms/test/tokens");
    rep.setIssuer(base + "/realms/test");
    rep.setJwksUri(base + "/realms/test/jwks");
    rep.setLogoutEndpoint(base + "/realms/test/logout");
    return rep;
}
 
Example #22
Source File: KeycloakLinkedAccountsProvider.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
/**
 * @see io.apicurio.hub.api.security.ILinkedAccountsProvider#initiateLinkedAccount(io.apicurio.hub.core.beans.LinkedAccountType, java.lang.String, java.lang.String)
 */
@Override
public InitiatedLinkedAccount initiateLinkedAccount(LinkedAccountType accountType, String redirectUri,
        String nonce) {
    String authServerRootUrl = config.getKeycloakAuthUrl();
    String realm = config.getKeycloakRealm();
    String provider = accountType.alias();

    KeycloakSecurityContext session = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
    AccessToken token = session.getToken();

    String clientId = token.getIssuedFor();
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    String input = nonce + token.getSessionState() + clientId + provider;
    byte[] check = md.digest(input.getBytes(StandardCharsets.UTF_8));
    String hash = Base64Url.encode(check);
    String accountLinkUrl = KeycloakUriBuilder.fromUri(authServerRootUrl)
        .path("/realms/{realm}/broker/{provider}/link").queryParam("nonce", nonce)
        .queryParam("hash", hash).queryParam("client_id", clientId)
        .queryParam("redirect_uri", redirectUri).build(realm, provider).toString();

    logger.debug("Account Link URL: {}", accountLinkUrl);

    // Return the URL that the browser should use to initiate the account linking
    InitiatedLinkedAccount rval = new InitiatedLinkedAccount();
    rval.setAuthUrl(accountLinkUrl);
    rval.setNonce(nonce);
    return rval;
}
 
Example #23
Source File: Controller.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public String getAccountUri(HttpServletRequest req) {
    KeycloakSecurityContext session = getSession(req);
    String baseUrl = getAuthServerBaseUrl(req);
    String realm = session.getRealm();
    return KeycloakUriBuilder.fromUri(baseUrl).path(ServiceUrlConstants.ACCOUNT_SERVICE_PATH)
            .queryParam("referrer", "app-profile-jee").build(realm).toString();

}
 
Example #24
Source File: UndertowHttpFacade.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public String getURI() {
    KeycloakUriBuilder uriBuilder = KeycloakUriBuilder.fromUri(exchange.getRequestURI())
            .replaceQuery(exchange.getQueryString());
    if (!exchange.isHostIncludedInRequestURI()) uriBuilder.scheme(exchange.getRequestScheme()).host(exchange.getHostAndPort());
    return uriBuilder.build().toString();
}
 
Example #25
Source File: FilterSamlSessionStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public String getRedirectUri() {
    HttpSession session = request.getSession(false);
    if (session == null) return null;
    String redirect = (String)session.getAttribute(REDIRECT_URI);
    if (redirect == null) {
        String contextPath = request.getContextPath();
        String baseUri = KeycloakUriBuilder.fromUri(request.getRequestURL().toString()).replacePath(contextPath).build().toString();
        return SamlUtil.getRedirectTo(facade, contextPath, baseUri);
    }
    return redirect;
}
 
Example #26
Source File: CatalinaSamlSessionStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public String getRedirectUri() {
    String redirect = (String)getSession(true).getAttribute(SAML_REDIRECT_URI);
    if (redirect == null) {
        String contextPath = request.getContextPath();
        String baseUri = KeycloakUriBuilder.fromUri(request.getRequestURL().toString()).replacePath(contextPath).build().toString();
        return SamlUtil.getRedirectTo(facade, contextPath, baseUri);
    }
    return redirect;
}
 
Example #27
Source File: ServletSamlSessionStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public String getRedirectUri() {
    final ServletRequestContext sc = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    HttpSessionImpl session = sc.getCurrentServletContext().getSession(exchange, true);
    String redirect = (String)session.getAttribute(SAML_REDIRECT_URI);
    if (redirect == null) {
        ServletHttpFacade facade = new ServletHttpFacade(exchange);
        HttpServletRequest req = (HttpServletRequest)sc.getServletRequest();
        String contextPath = req.getContextPath();
        String baseUri = KeycloakUriBuilder.fromUri(req.getRequestURL().toString()).replacePath(contextPath).build().toString();
        return SamlUtil.getRedirectTo(facade, contextPath, baseUri);
    }
    return redirect;
}
 
Example #28
Source File: ServletSamlSessionStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void saveRequest() {
    SavedRequest.trySaveRequest(exchange);
    final ServletRequestContext sc = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    HttpSessionImpl session = sc.getCurrentServletContext().getSession(exchange, true);
    KeycloakUriBuilder uriBuilder = KeycloakUriBuilder.fromUri(exchange.getRequestURI())
            .replaceQuery(exchange.getQueryString());
    if (!exchange.isHostIncludedInRequestURI()) uriBuilder.scheme(exchange.getRequestScheme()).host(exchange.getHostAndPort());
    String uri = uriBuilder.build().toString();

    session.setAttribute(SAML_REDIRECT_URI, uri);

}
 
Example #29
Source File: JettySamlSessionStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public String getRedirectUri() {
    String redirect = (String)request.getSession(true).getAttribute(SAML_REDIRECT_URI);
    if (redirect == null) {
        String contextPath = request.getContextPath();
        String baseUri = KeycloakUriBuilder.fromUri(request.getRequestURL().toString()).replacePath(contextPath).build().toString();
        return SamlUtil.getRedirectTo(facade, contextPath, baseUri);
    }
    return redirect;
}
 
Example #30
Source File: AbstractSamlAuthenticationHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void verifyRedirectBindingSignature(String paramKey, KeyLocator keyLocator, String keyId) throws VerificationException {
    String request = facade.getRequest().getQueryParamValue(paramKey);
    String algorithm = facade.getRequest().getQueryParamValue(GeneralConstants.SAML_SIG_ALG_REQUEST_KEY);
    String signature = facade.getRequest().getQueryParamValue(GeneralConstants.SAML_SIGNATURE_REQUEST_KEY);
    String decodedAlgorithm = facade.getRequest().getQueryParamValue(GeneralConstants.SAML_SIG_ALG_REQUEST_KEY);

    if (request == null) {
        throw new VerificationException("SAML Request was null");
    }
    if (algorithm == null) throw new VerificationException("SigAlg was null");
    if (signature == null) throw new VerificationException("Signature was null");

    // Shibboleth doesn't sign the document for redirect binding.
    // todo maybe a flag?

    String relayState = facade.getRequest().getQueryParamValue(GeneralConstants.RELAY_STATE);
    KeycloakUriBuilder builder = KeycloakUriBuilder.fromPath("/")
            .queryParam(paramKey, request);
    if (relayState != null) {
        builder.queryParam(GeneralConstants.RELAY_STATE, relayState);
    }
    builder.queryParam(GeneralConstants.SAML_SIG_ALG_REQUEST_KEY, algorithm);
    String rawQuery = builder.build().getRawQuery();

    try {
        //byte[] decodedSignature = RedirectBindingUtil.urlBase64Decode(signature);
        byte[] decodedSignature = Base64.decode(signature);
        byte[] rawQueryBytes = rawQuery.getBytes("UTF-8");

        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.getFromXmlMethod(decodedAlgorithm);

        if (! validateRedirectBindingSignature(signatureAlgorithm, rawQueryBytes, decodedSignature, keyLocator, keyId)) {
            throw new VerificationException("Invalid query param signature");
        }
    } catch (Exception e) {
        throw new VerificationException(e);
    }
}