Search in sources :

Example 91 with HttpHeaders

use of javax.ws.rs.core.HttpHeaders in project neo4j by neo4j.

the class AbstractCypherResource method executeStatementsInNewTransaction.

@POST
public Response executeStatementsInNewTransaction(InputEventStream inputEventStream, @Context HttpServletRequest request, @Context HttpHeaders headers) {
    try (var memoryTracker = createMemoryTracker()) {
        InputEventStream inputStream = ensureNotNull(inputEventStream);
        var graphDatabaseAPI = httpTransactionManager.getGraphDatabaseAPI(databaseName);
        return graphDatabaseAPI.map(databaseAPI -> {
            if (isDatabaseNotAvailable(databaseAPI)) {
                return createNonAvailableDatabaseResponse(inputStream.getParameters());
            }
            memoryTracker.allocateHeap(Invocation.SHALLOW_SIZE);
            final TransactionFacade transactionFacade = httpTransactionManager.createTransactionFacade(databaseAPI, memoryTracker);
            TransactionHandle transactionHandle = createNewTransactionHandle(transactionFacade, request, headers, memoryTracker, false);
            Invocation invocation = new Invocation(log, transactionHandle, uriScheme.txCommitUri(transactionHandle.getId()), memoryPool, inputStream, false);
            OutputEventStreamImpl outputStream = new OutputEventStreamImpl(inputStream.getParameters(), transactionHandle, uriScheme, invocation::execute);
            return Response.created(transactionHandle.uri()).entity(outputStream).build();
        }).orElse(createNonExistentDatabaseResponse(inputStream.getParameters()));
    }
}
Also used : PathParam(javax.ws.rs.PathParam) Neo4jError(org.neo4j.server.rest.Neo4jError) Log(org.neo4j.logging.Log) TransactionUriScheme(org.neo4j.server.http.cypher.format.api.TransactionUriScheme) Status(org.neo4j.kernel.api.exceptions.Status) Path(javax.ws.rs.Path) LoginContext(org.neo4j.internal.kernel.api.security.LoginContext) LocalMemoryTracker(org.neo4j.memory.LocalMemoryTracker) Objects.requireNonNullElse(java.util.Objects.requireNonNullElse) HttpServletRequest(javax.servlet.http.HttpServletRequest) Map(java.util.Map) UriBuilder(javax.ws.rs.core.UriBuilder) URI(java.net.URI) MemoryTracker(org.neo4j.memory.MemoryTracker) DELETE(javax.ws.rs.DELETE) HttpHeaderUtils.getTransactionTimeout(org.neo4j.server.web.HttpHeaderUtils.getTransactionTimeout) Collections.emptyMap(java.util.Collections.emptyMap) POST(javax.ws.rs.POST) Context(javax.ws.rs.core.Context) InputEventStream(org.neo4j.server.http.cypher.format.api.InputEventStream) MemoryPool(org.neo4j.memory.MemoryPool) GraphDatabaseAPI(org.neo4j.kernel.internal.GraphDatabaseAPI) AuthorizedRequestWrapper(org.neo4j.server.rest.dbms.AuthorizedRequestWrapper) HttpHeaders(javax.ws.rs.core.HttpHeaders) Response(javax.ws.rs.core.Response) Optional(java.util.Optional) UriInfo(javax.ws.rs.core.UriInfo) InputEventStream(org.neo4j.server.http.cypher.format.api.InputEventStream) POST(javax.ws.rs.POST)

Example 92 with HttpHeaders

use of javax.ws.rs.core.HttpHeaders in project keycloak by keycloak.

the class JBossLoggingEventListenerProvider method setKeycloakContext.

private void setKeycloakContext(StringBuilder sb) {
    KeycloakContext context = session.getContext();
    UriInfo uriInfo = context.getUri();
    HttpHeaders headers = context.getRequestHeaders();
    if (uriInfo != null) {
        sb.append(", requestUri=");
        sb.append(uriInfo.getRequestUri().toString());
    }
    if (headers != null) {
        sb.append(", cookies=[");
        boolean f = true;
        for (Map.Entry<String, Cookie> e : headers.getCookies().entrySet()) {
            if (f) {
                f = false;
            } else {
                sb.append(", ");
            }
            sb.append(e.getValue().toString());
        }
        sb.append("]");
    }
}
Also used : Cookie(javax.ws.rs.core.Cookie) HttpHeaders(javax.ws.rs.core.HttpHeaders) KeycloakContext(org.keycloak.models.KeycloakContext) Map(java.util.Map) UriInfo(javax.ws.rs.core.UriInfo)

Example 93 with HttpHeaders

use of javax.ws.rs.core.HttpHeaders in project keycloak by keycloak.

the class AccountLoader method getAccountService.

@Path("/")
public Object getAccountService() {
    RealmModel realm = session.getContext().getRealm();
    ClientModel client = getAccountManagementClient(realm);
    HttpRequest request = session.getContext().getContextObject(HttpRequest.class);
    HttpHeaders headers = session.getContext().getRequestHeaders();
    MediaType content = headers.getMediaType();
    List<MediaType> accepts = headers.getAcceptableMediaTypes();
    Theme theme = getTheme(session);
    boolean deprecatedAccount = isDeprecatedFormsAccountConsole(theme);
    UriInfo uriInfo = session.getContext().getUri();
    if (request.getHttpMethod().equals(HttpMethod.OPTIONS)) {
        return new CorsPreflightService(request);
    } else if ((accepts.contains(MediaType.APPLICATION_JSON_TYPE) || MediaType.APPLICATION_JSON_TYPE.equals(content)) && !uriInfo.getPath().endsWith("keycloak.json")) {
        return getAccountRestService(client, null);
    } else {
        if (deprecatedAccount) {
            AccountFormService accountFormService = new AccountFormService(realm, client, event);
            ResteasyProviderFactory.getInstance().injectProperties(accountFormService);
            accountFormService.init();
            return accountFormService;
        } else {
            AccountConsole console = new AccountConsole(realm, client, theme);
            ResteasyProviderFactory.getInstance().injectProperties(console);
            console.init();
            return console;
        }
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) HttpRequest(org.jboss.resteasy.spi.HttpRequest) ClientModel(org.keycloak.models.ClientModel) HttpHeaders(javax.ws.rs.core.HttpHeaders) MediaType(javax.ws.rs.core.MediaType) Theme(org.keycloak.theme.Theme) UriInfo(javax.ws.rs.core.UriInfo) Path(javax.ws.rs.Path)

Example 94 with HttpHeaders

use of javax.ws.rs.core.HttpHeaders in project keycloak by keycloak.

the class AuthenticationManager method finishBrowserLogout.

public static Response finishBrowserLogout(KeycloakSession session, RealmModel realm, UserSessionModel userSession, UriInfo uriInfo, ClientConnection connection, HttpHeaders headers) {
    final AuthenticationSessionManager asm = new AuthenticationSessionManager(session);
    AuthenticationSessionModel logoutAuthSession = createOrJoinLogoutSession(session, realm, asm, userSession, true);
    checkUserSessionOnlyHasLoggedOutClients(realm, userSession, logoutAuthSession);
    // For resolving artifact we don't need any cookie, all details are stored in session storage so we can remove
    expireIdentityCookie(realm, uriInfo, connection);
    expireRememberMeCookie(realm, uriInfo, connection);
    String method = userSession.getNote(KEYCLOAK_LOGOUT_PROTOCOL);
    EventBuilder event = new EventBuilder(realm, session, connection);
    LoginProtocol protocol = session.getProvider(LoginProtocol.class, method);
    protocol.setRealm(realm).setHttpHeaders(headers).setUriInfo(uriInfo).setEventBuilder(event);
    Response response = protocol.finishLogout(userSession);
    // It may be possible that there are some client sessions that are still in LOGGING_OUT state
    long numberOfUnconfirmedSessions = userSession.getAuthenticatedClientSessions().values().stream().filter(clientSessionModel -> CommonClientSessionModel.Action.LOGGING_OUT.name().equals(clientSessionModel.getAction())).count();
    // If logout flow end up correctly there should be at maximum 1 client session in LOGGING_OUT action, if there are more, something went wrong
    if (numberOfUnconfirmedSessions > 1) {
        logger.warnf("There are more than one clientSession in logging_out state. Perhaps some client did not finish logout flow correctly.");
    }
    // LOGGED_OUT action can remove UserSession
    if (numberOfUnconfirmedSessions >= 1) {
        userSession.setState(UserSessionModel.State.LOGGED_OUT_UNCONFIRMED);
    } else {
        userSession.setState(UserSessionModel.State.LOGGED_OUT);
    }
    // Do not remove user session, it will be removed when last clientSession will be logged out
    if (numberOfUnconfirmedSessions < 1) {
        session.sessions().removeUserSession(realm, userSession);
    }
    session.authenticationSessions().removeRootAuthenticationSession(realm, logoutAuthSession.getParentSession());
    return response;
}
Also used : BackchannelLogoutResponse(org.keycloak.protocol.oidc.BackchannelLogoutResponse) Response(javax.ws.rs.core.Response) DefaultClientSessionContext(org.keycloak.services.util.DefaultClientSessionContext) ActionTokenStoreProvider(org.keycloak.models.ActionTokenStoreProvider) Error(org.keycloak.protocol.LoginProtocol.Error) ErrorResponseException(org.keycloak.services.ErrorResponseException) Map(java.util.Map) ClientConnection(org.keycloak.common.ClientConnection) UriBuilder(javax.ws.rs.core.UriBuilder) Time(org.keycloak.common.util.Time) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) AuthenticationProcessor(org.keycloak.authentication.AuthenticationProcessor) Set(java.util.Set) AbstractUsernameFormAuthenticator(org.keycloak.authentication.authenticators.browser.AbstractUsernameFormAuthenticator) SecretGenerator(org.keycloak.common.util.SecretGenerator) Stream(java.util.stream.Stream) AuthenticationFlowException(org.keycloak.authentication.AuthenticationFlowException) SessionTimeoutHelper(org.keycloak.models.utils.SessionTimeoutHelper) LoginActionsService(org.keycloak.services.resources.LoginActionsService) UriInfo(javax.ws.rs.core.UriInfo) OAuth2Constants(org.keycloak.OAuth2Constants) LoginProtocol(org.keycloak.protocol.LoginProtocol) Constants(org.keycloak.models.Constants) TokenManager(org.keycloak.protocol.oidc.TokenManager) TokenUtil(org.keycloak.util.TokenUtil) UserModel(org.keycloak.models.UserModel) ClientSessionContext(org.keycloak.models.ClientSessionContext) Predicate(org.keycloak.TokenVerifier.Predicate) TokenVerifier(org.keycloak.TokenVerifier) CommonClientSessionModel(org.keycloak.sessions.CommonClientSessionModel) Base64Url(org.keycloak.common.util.Base64Url) BackchannelLogoutResponse(org.keycloak.protocol.oidc.BackchannelLogoutResponse) AuthenticationFlowError(org.keycloak.authentication.AuthenticationFlowError) ConsoleDisplayMode(org.keycloak.authentication.ConsoleDisplayMode) IdentityBrokerService(org.keycloak.services.resources.IdentityBrokerService) KeycloakSession(org.keycloak.models.KeycloakSession) AuthorizationDetails(org.keycloak.rar.AuthorizationDetails) HttpRequest(org.jboss.resteasy.spi.HttpRequest) EventType(org.keycloak.events.EventType) P3PHelper(org.keycloak.services.util.P3PHelper) RequiredActionProvider(org.keycloak.authentication.RequiredActionProvider) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException) LoginFormsProvider(org.keycloak.forms.login.LoginFormsProvider) URLDecoder(java.net.URLDecoder) ActionTokenKeyModel(org.keycloak.models.ActionTokenKeyModel) RequiredActionContextResult(org.keycloak.authentication.RequiredActionContextResult) RequiredActionFactory(org.keycloak.authentication.RequiredActionFactory) NewCookie(javax.ws.rs.core.NewCookie) Messages(org.keycloak.services.messages.Messages) DefaultActionTokenKey(org.keycloak.authentication.actiontoken.DefaultActionTokenKey) SignatureVerifierContext(org.keycloak.crypto.SignatureVerifierContext) AccessToken(org.keycloak.representations.AccessToken) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) URI(java.net.URI) SystemClientUtil(org.keycloak.models.utils.SystemClientUtil) VerificationException(org.keycloak.common.VerificationException) DeviceGrantType.isOAuth2DeviceVerificationFlow(org.keycloak.protocol.oidc.grants.device.DeviceGrantType.isOAuth2DeviceVerificationFlow) ClientScopeModel(org.keycloak.models.ClientScopeModel) RealmModel(org.keycloak.models.RealmModel) InitiatedActionSupport(org.keycloak.authentication.InitiatedActionSupport) AuthenticatorUtil(org.keycloak.authentication.AuthenticatorUtil) Collectors(java.util.stream.Collectors) Cookie(javax.ws.rs.core.Cookie) Objects(java.util.Objects) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Response(javax.ws.rs.core.Response) Details(org.keycloak.events.Details) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) Optional(java.util.Optional) UnsupportedEncodingException(java.io.UnsupportedEncodingException) RequiredActionProviderModel(org.keycloak.models.RequiredActionProviderModel) ClientModel(org.keycloak.models.ClientModel) RealmsResource(org.keycloak.services.resources.RealmsResource) Profile(org.keycloak.common.Profile) SameSiteAttributeValue(org.keycloak.common.util.ServerCookie.SameSiteAttributeValue) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) Logger(org.jboss.logging.Logger) ServicesLogger(org.keycloak.services.ServicesLogger) TokenTypeCheck(org.keycloak.TokenVerifier.TokenTypeCheck) RequiredActionContext(org.keycloak.authentication.RequiredActionContext) SignatureProvider(org.keycloak.crypto.SignatureProvider) EventBuilder(org.keycloak.events.EventBuilder) CookieHelper(org.keycloak.services.util.CookieHelper) UserConsentModel(org.keycloak.models.UserConsentModel) OIDCAdvancedConfigWrapper(org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper) LinkedList(java.util.LinkedList) DisplayTypeRequiredActionFactory(org.keycloak.authentication.DisplayTypeRequiredActionFactory) IdentityProvider(org.keycloak.broker.provider.IdentityProvider) Errors(org.keycloak.events.Errors) CORRESPONDING_SESSION_ID(org.keycloak.models.UserSessionModel.CORRESPONDING_SESSION_ID) UserSessionModel(org.keycloak.models.UserSessionModel) AuthorizationContextUtil(org.keycloak.services.util.AuthorizationContextUtil) URLEncoder(java.net.URLEncoder) LogoutRequestContext(org.keycloak.services.clientpolicy.context.LogoutRequestContext) CookieHelper.getCookie(org.keycloak.services.util.CookieHelper.getCookie) Urls(org.keycloak.services.Urls) Collections(java.util.Collections) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) EventBuilder(org.keycloak.events.EventBuilder) LoginProtocol(org.keycloak.protocol.LoginProtocol) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol)

Example 95 with HttpHeaders

use of javax.ws.rs.core.HttpHeaders in project keycloak by keycloak.

the class CookieHelper method getInternalCookieValue.

private static Set<String> getInternalCookieValue(String name) {
    HttpHeaders headers = Resteasy.getContextData(HttpHeaders.class);
    Set<String> cookiesVal = new HashSet<>();
    // check for cookies in the request headers
    cookiesVal.addAll(parseCookie(headers.getRequestHeaders().getFirst(HttpHeaders.COOKIE), name));
    // get cookies from the cookie field
    Cookie cookie = headers.getCookies().get(name);
    if (cookie != null) {
        logger.debugv("{0} cookie found in the cookie field", name);
        cookiesVal.add(cookie.getValue());
    }
    return cookiesVal;
}
Also used : ServerCookie(org.keycloak.common.util.ServerCookie) Cookie(javax.ws.rs.core.Cookie) HttpHeaders(javax.ws.rs.core.HttpHeaders) HashSet(java.util.HashSet)

Aggregations

HttpHeaders (javax.ws.rs.core.HttpHeaders)95 Test (org.junit.Test)57 Message (org.apache.cxf.message.Message)31 Optional (java.util.Optional)13 HttpServletRequest (javax.servlet.http.HttpServletRequest)13 UriInfo (javax.ws.rs.core.UriInfo)12 CatalogFramework (ddf.catalog.CatalogFramework)10 Locale (java.util.Locale)10 Response (javax.ws.rs.core.Response)10 MultipartBody (org.apache.cxf.jaxrs.ext.multipart.MultipartBody)10 JsonObject (com.google.gson.JsonObject)9 MediaType (javax.ws.rs.core.MediaType)9 ByteArrayInputStream (java.io.ByteArrayInputStream)8 Map (java.util.Map)8 Cookie (javax.ws.rs.core.Cookie)8 IOException (java.io.IOException)7 Collections (java.util.Collections)7 WebApplicationException (javax.ws.rs.WebApplicationException)7 URI (java.net.URI)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6