org.apache.cxf.jaxrs.impl.HttpHeadersImpl Java Examples

The following examples show how to use org.apache.cxf.jaxrs.impl.HttpHeadersImpl. 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: OAuthHandler.java    From product-private-paas with Apache License 2.0 6 votes vote down vote up
public Response handle(Message message, ClassResourceInfo classResourceInfo) {
    try {
        OAuth2TokenValidationResponseDTO respDTO;
        ValidationServiceClient validationServiceClient = new ValidationServiceClient(oauthValidationEndpoint,
                username, password);
        HttpHeaders httpHeaders = new HttpHeadersImpl(message);
        String header = httpHeaders.getRequestHeaders().getFirst("Authorization");
        // if the authorization token has Bearer..
        if (header.startsWith("Bearer ")) {
            String accessToken = header.substring(7).trim();
            respDTO = validationServiceClient.validateAuthenticationRequest(accessToken); //TODO : send scope params
            boolean valid = respDTO.getValid();
            if (!valid) {
                // authorization failure..
                return Response.status(Response.Status.FORBIDDEN).build();
            }
        }
    } catch (Exception e) {
        log.error("Error while validating access token", e);
        return Response.status(Response.Status.FORBIDDEN).build();
    }
    AuthenticationContext.setAuthenticated(true);
    return null;
}
 
Example #2
Source File: OAuthHandler.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
public Response handle(Message message, ClassResourceInfo classResourceInfo) {
    try {
        OAuth2TokenValidationResponseDTO respDTO;
        ValidationServiceClient validationServiceClient = new
                ValidationServiceClient(oauthValidationEndpoint, username, password);
        HttpHeaders httpHeaders = new HttpHeadersImpl(message);
        String header = httpHeaders.getRequestHeaders().getFirst("Authorization");
        // if the authorization token has Bearer..
        if (header.startsWith("Bearer ")) {
            String accessToken = header.substring(7).trim();
            respDTO = validationServiceClient.validateAuthenticationRequest(accessToken); //TODO : send scope params
            boolean valid = respDTO.getValid();
            if (!valid) {
                // authorization failure..
                return Response.status(Response.Status.FORBIDDEN).build();
            }
        }
    } catch (Exception e) {
        log.error("Error while validating access token", e);
        return Response.status(Response.Status.FORBIDDEN).build();
    }
    AuthenticationContext.setAuthenticated(true);
    return null;
}
 
Example #3
Source File: JAXRSUtilsTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testPerRequestContextFields() throws Exception {

    ClassResourceInfo cri = new ClassResourceInfo(Customer.class, true);
    cri.setResourceProvider(new PerRequestResourceProvider(Customer.class));
    OperationResourceInfo ori = new OperationResourceInfo(Customer.class.getMethod("postConstruct",
                                                                                   new Class[]{}), cri);

    Customer c = new Customer();

    Message m = createMessage();
    m.put(Message.PROTOCOL_HEADERS, new HashMap<String, List<String>>());
    HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
    m.put(AbstractHTTPDestination.HTTP_RESPONSE, response);

    InjectionUtils.injectContextFields(c, ori.getClassResourceInfo(), m);
    assertSame(UriInfoImpl.class, c.getUriInfo2().getClass());
    assertSame(HttpHeadersImpl.class, c.getHeaders().getClass());
    assertSame(RequestImpl.class, c.getRequest().getClass());
    assertSame(SecurityContextImpl.class, c.getSecurityContext().getClass());
    assertSame(ProvidersImpl.class, c.getBodyWorkers().getClass());

}
 
Example #4
Source File: BinaryDataProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void copyInputToOutput(InputStream is, OutputStream os,
        Annotation[] anns, MultivaluedMap<String, Object> outHeaders) throws IOException {
    if (isRangeSupported()) {
        Message inMessage = PhaseInterceptorChain.getCurrentMessage().getExchange().getInMessage();
        handleRangeRequest(is, os, new HttpHeadersImpl(inMessage), outHeaders);
    } else {
        boolean nioWrite = AnnotationUtils.getAnnotation(anns, UseNio.class) != null;
        if (nioWrite) {
            ContinuationProvider provider = getContinuationProvider();
            if (provider != null) {
                copyUsingNio(is, os, provider.getContinuation());
            }
            return;
        }
        if (closeResponseInputStream) {
            IOUtils.copyAndCloseInput(is, os, bufferSize);
        } else {
            IOUtils.copy(is, os, bufferSize);
        }

    }
}
 
Example #5
Source File: JAXRSUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static Object processHeaderParam(Message m,
                                         String header,
                                         Class<?> pClass,
                                         Type genericType,
                                         Annotation[] paramAnns,
                                         String defaultValue) {

    List<String> values = new HttpHeadersImpl(m).getRequestHeader(header);
    if (values != null && values.isEmpty()) {
        values = null;
    }
    return InjectionUtils.createParameterObject(values,
                                                pClass,
                                                genericType,
                                                paramAnns,
                                                defaultValue,
                                                false,
                                                ParameterType.HEADER,
                                                m);


}
 
Example #6
Source File: JAXRSUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static Object readFromMessageBodyReader(List<ReaderInterceptor> readers,
                                               Class<?> targetTypeClass,
                                               Type parameterType,
                                               Annotation[] parameterAnnotations,
                                               InputStream is,
                                               MediaType mediaType,
                                               Message m) throws IOException, WebApplicationException {

    // Verbose but avoids an extra context instantiation for the typical path
    if (readers.size() > 1) {
        ReaderInterceptor first = readers.remove(0);
        ReaderInterceptorContext context = new ReaderInterceptorContextImpl(targetTypeClass,
                                                                        parameterType,
                                                                        parameterAnnotations,
                                                                        is,
                                                                        m,
                                                                        readers);

        return first.aroundReadFrom(context);
    }
    MessageBodyReader<?> provider = ((ReaderInterceptorMBR)readers.get(0)).getMBR();
    @SuppressWarnings("rawtypes")
    Class cls = targetTypeClass;
    return provider.readFrom(
              cls, parameterType, parameterAnnotations, mediaType,
              new HttpHeadersImpl(m).getRequestHeaders(), is);
}
 
Example #7
Source File: AbstractAuthenticationAuthorizationHandler.java    From product-private-paas with Apache License 2.0 5 votes vote down vote up
public Response handleRequest(Message message, ClassResourceInfo classResourceInfo) {
    HttpHeaders headers = new HttpHeadersImpl(message);
    List<String> authHeader = headers.getRequestHeader(HttpHeaders.AUTHORIZATION);
    if (log.isDebugEnabled()) {
        log.debug("Executing " + this.getClass());
    }
    if (!AuthenticationContext.isAthenticated() && authHeader != null && authHeader.size() > 0 &&
            canHandle(authHeader.get(0).trim().split(" ")[0])) {
        return handle(message, classResourceInfo);
    }
    // give the control to the next handler
    return null;

}
 
Example #8
Source File: HmacAuthInterceptor.java    From gazpachoquest with GNU General Public License v3.0 5 votes vote down vote up
public void addHeader(Message message, String name, String value) {
    HttpHeaders requestHeaders = new HttpHeadersImpl(message);
    MultivaluedMap<String, String> newHeaders = new MetadataMap<String, String>();
    newHeaders.putAll(requestHeaders.getRequestHeaders());
    newHeaders.put(name, Arrays.asList(value));
    message.put(Message.PROTOCOL_HEADERS, newHeaders);
}
 
Example #9
Source File: AbstractServiceProviderFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected boolean checkSecurityContext(Message m) {
    HttpHeaders headers = new HttpHeadersImpl(m);
    Map<String, Cookie> cookies = headers.getCookies();

    Cookie securityContextCookie = cookies.get(SSOConstants.SECURITY_CONTEXT_TOKEN);

    ResponseState responseState = getValidResponseState(securityContextCookie, m);
    if (responseState == null) {
        return false;
    }

    if (!isSupportUnsolicited()) {
        Cookie relayStateCookie = cookies.get(SSOConstants.RELAY_STATE);
        if (relayStateCookie == null) {
            reportError("MISSING_RELAY_COOKIE");
            return false;
        }
        String originalRelayState = responseState.getRelayState();
        if (!originalRelayState.equals(relayStateCookie.getValue())) {
            // perhaps the response state should also be removed
            reportError("INVALID_RELAY_STATE");
            return false;
        }
    }
    try {
        String assertion = responseState.getAssertion();
        SamlAssertionWrapper assertionWrapper =
            new SamlAssertionWrapper(
                StaxUtils.read(new StringReader(assertion)).getDocumentElement());
        setSecurityContext(m, assertionWrapper);
    } catch (Exception ex) {
        reportError("INVALID_RESPONSE_STATE");
        return false;
    }
    return true;
}
 
Example #10
Source File: JAXRSUtilsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testHttpContextParameters() throws Exception {

    ClassResourceInfo cri = new ClassResourceInfo(Customer.class, true);
    OperationResourceInfo ori =
        new OperationResourceInfo(
            Customer.class.getMethod("testParams",
                                     new Class[]{UriInfo.class,
                                                 HttpHeaders.class,
                                                 Request.class,
                                                 SecurityContext.class,
                                                 Providers.class,
                                                 String.class,
                                                 List.class}),
            cri);
    ori.setHttpMethod("GET");
    MultivaluedMap<String, String> headers = new MetadataMap<>();
    headers.add("Foo", "bar, baz");

    Message m = createMessage();
    m.put("org.apache.cxf.http.header.split", "true");
    m.put(Message.PROTOCOL_HEADERS, headers);

    List<Object> params =
        JAXRSUtils.processParameters(ori, new MetadataMap<String, String>(), m);
    assertEquals("7 parameters expected", 7, params.size());
    assertSame(UriInfoImpl.class, params.get(0).getClass());
    assertSame(HttpHeadersImpl.class, params.get(1).getClass());
    assertSame(RequestImpl.class, params.get(2).getClass());
    assertSame(SecurityContextImpl.class, params.get(3).getClass());
    assertSame(ProvidersImpl.class, params.get(4).getClass());
    assertSame(String.class, params.get(5).getClass());
    assertEquals("Wrong header param", "bar", params.get(5));
    List<String> values = (List<String>)params.get(6);
    assertEquals("Wrong headers size", 2, values.size());
    assertEquals("Wrong 1st header param", "bar", values.get(0));
    assertEquals("Wrong 2nd header param", "baz", values.get(1));
}
 
Example #11
Source File: JAXRSUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static Object createHttpHeaders(Message m, Class<?> ctxClass) {
    if (MessageUtils.isRequestor(m)) {
        m = m.getExchange() != null ? m.getExchange().getOutMessage() : m;
    }
    return HttpHeaders.class.isAssignableFrom(ctxClass) ? new HttpHeadersImpl(m)
        : new ProtocolHeadersImpl(m);
}
 
Example #12
Source File: JAXRSUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static Object processCookieParam(Message m, String cookieName,
                          Class<?> pClass, Type genericType,
                          Annotation[] paramAnns, String defaultValue) {
    Cookie c = new HttpHeadersImpl(m).getCookies().get(cookieName);

    if (c == null && defaultValue != null) {
        c = Cookie.valueOf(cookieName + '=' + defaultValue);
    }
    if (c == null) {
        return null;
    }

    if (pClass.isAssignableFrom(Cookie.class)) {
        return c;
    }
    String value = InjectionUtils.isSupportedCollectionOrArray(pClass)
        && InjectionUtils.getActualType(genericType) == Cookie.class
        ? c.toString() : c.getValue();
    return InjectionUtils.createParameterObject(Collections.singletonList(value),
                                                pClass,
                                                genericType,
                                                paramAnns,
                                                null,
                                                false,
                                                ParameterType.COOKIE,
                                                m);
}
 
Example #13
Source File: HttpUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static String getProtocolHeader(Message m, String name, String defaultValue, boolean setOnMessage) {
    String value = (String)m.get(name);
    if (value == null) {
        value = new HttpHeadersImpl(m).getRequestHeaders().getFirst(name);
        if (value != null && setOnMessage) {
            m.put(name, value);
        }
    }
    return value == null ? defaultValue : value;
}
 
Example #14
Source File: OAuthHandler.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override
public Response handle(Message message, ClassResourceInfo classResourceInfo) {
    try {
        HttpHeaders httpHeaders = new HttpHeadersImpl(message);
        String header = httpHeaders.getRequestHeaders().getFirst("Authorization");
        // if the authorization token has Bearer..
        if (header.startsWith(BEARER)) {
            String accessToken = header.substring(7).trim();
            boolean valid;
            String appId_in_token = extractAppIdFromIdToken(accessToken);
            String requestUrl = (String) message.get(Message.REQUEST_URI);
            String basePath = (String) message.get(Message.BASE_PATH);
            String requestedAppId = extractApplicationIdFromUrl(requestUrl, basePath);

            if (org.apache.commons.lang3.StringUtils.isEmpty(appId_in_token) || org.apache.commons.lang3.StringUtils.isEmpty(requestedAppId)) {
                valid = false;
            } else {
                valid = appId_in_token.equals(requestedAppId);
                if(!valid){
                    log.error("The token presented is only valid for " + appId_in_token + " , but it tries to access metadata for " + requestedAppId);
                }
            }

            if (!valid) {
                return Response.status(Response.Status.FORBIDDEN).build();
            }
        }else{
            return Response.status(Response.Status.FORBIDDEN).build();
        }
    } catch (Exception e) {
        log.error("Error while validating access token", e);
        return Response.status(Response.Status.FORBIDDEN).build();
    }

    AuthenticationContext.setAuthenticated(true);
    return null;
}
 
Example #15
Source File: AbstractAuthenticationAuthorizationHandler.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override
public Response handleRequest(Message message, ClassResourceInfo classResourceInfo) {
    HttpHeaders headers = new HttpHeadersImpl(message);

    if (!StringUtils.isEmpty(headers.getRequestHeaders().getFirst(HttpHeaders.AUTHORIZATION))) {
        return handle(message, classResourceInfo);
    }else{
        // Currently there is only one handler
        return Response.status(Response.Status.FORBIDDEN).build();
    }
}
 
Example #16
Source File: AbstractAuthenticationAuthorizationHandler.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
public Response handleRequest(Message message, ClassResourceInfo classResourceInfo) {
    HttpHeaders headers = new HttpHeadersImpl(message);
    List<String> authHeader = headers.getRequestHeader(HttpHeaders.AUTHORIZATION);
    if (log.isDebugEnabled()) {
        log.debug("Executing " + this.getClass());
    }
    if (!AuthenticationContext.isAthenticated() && authHeader != null && authHeader.size() > 0 &&
            canHandle(authHeader.get(0).trim().split(" ")[0])) {
        return handle(message, classResourceInfo);
    }
    // give the control to the next handler
    return null;
}
 
Example #17
Source File: ServerOutInterceptor.java    From peer-os with Apache License 2.0 5 votes vote down vote up
/**
 * Intercepts a message. interceptor chain will take care of this.
 */
@Override
public void handleMessage( final Message message )
{
    try
    {
        if ( InterceptorState.SERVER_OUT.isActive( message ) )
        {
            //obtain client request
            HttpServletRequest req = ( HttpServletRequest ) message.getExchange().getInMessage()
                                                                   .get( AbstractHTTPDestination.HTTP_REQUEST );

            if ( req.getLocalPort() == Common.DEFAULT_PUBLIC_SECURE_PORT )
            {
                HttpHeaders headers = new HttpHeadersImpl( message.getExchange().getInMessage() );
                String subutaiHeader = headers.getHeaderString( Common.SUBUTAI_HTTP_HEADER );
                String path = req.getRequestURI();

                if ( path.startsWith( "/rest/v1/peer" ) )
                {
                    handlePeerMessage( subutaiHeader, message );
                }
                else
                {
                    final String prefix = "/rest/v1/env";
                    if ( path.startsWith( prefix ) )
                    {
                        String s = path.substring( prefix.length() + 1 );
                        String environmentId = s.substring( 0, s.indexOf( "/" ) );
                        handleEnvironmentMessage( subutaiHeader, environmentId, message );
                    }
                }
            }
        }
    }
    catch ( Exception e )
    {
        throw new Fault( e );
    }
}
 
Example #18
Source File: AccessControlInterceptor.java    From peer-os with Apache License 2.0 4 votes vote down vote up
protected Session authenticateAccess( Message message, HttpServletRequest request )
{
    String sptoken;

    if ( message == null )
    {
        //***********internal auth ********* for registration , 8444 port and 8443 open REST endpoints
        return identityManager.loginSystemUser();
    }
    else
    {
        String bearerToken = getBearerToken( request );
        if ( bearerToken != null )
        {
            return identityManager.login( request, message );
        }
        else
        {
            sptoken = request.getParameter( "sptoken" );

            if ( StringUtils.isBlank( sptoken ) )
            {
                HttpHeaders headers = new HttpHeadersImpl( message.getExchange().getInMessage() );
                sptoken = headers.getHeaderString( "sptoken" );
            }

            //******************Get sptoken from cookies *****************

            if ( StringUtils.isBlank( sptoken ) )
            {
                Cookie[] cookies = request.getCookies();
                for ( final Cookie cookie : cookies )
                {
                    if ( "sptoken".equals( cookie.getName() ) )
                    {
                        sptoken = cookie.getValue();
                    }
                }
            }

            if ( StringUtils.isBlank( sptoken ) )
            {
                return null;
            }
            else
            {
                return identityManager.login( IdentityManager.TOKEN_ID, sptoken );
            }
        }
    }
}
 
Example #19
Source File: ProtocolHeadersImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
public ProtocolHeadersImpl(Message m) {
    httpHeaders = new HttpHeadersImpl(m);
}
 
Example #20
Source File: JAASAuthenticationFilter.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected Response handleAuthenticationException(SecurityException ex, Message m) {
    HttpHeaders headers = new HttpHeadersImpl(m);
    if (redirectURI != null && isRedirectPossible(headers)) {

        URI finalRedirectURI = null;

        if (!redirectURI.isAbsolute()) {
            String endpointAddress = HttpUtils.getEndpointAddress(m);
            Object basePathProperty = m.get(Message.BASE_PATH);
            if (ignoreBasePath && basePathProperty != null && !"/".equals(basePathProperty)) {
                int index = endpointAddress.lastIndexOf(basePathProperty.toString());
                if (index != -1) {
                    endpointAddress = endpointAddress.substring(0, index);
                }
            }
            finalRedirectURI = UriBuilder.fromUri(endpointAddress).path(redirectURI.toString()).build();
        } else {
            finalRedirectURI = redirectURI;
        }

        return Response.status(getRedirectStatus()).
                header(HttpHeaders.LOCATION, finalRedirectURI).build();
    }
    ResponseBuilder builder = Response.status(Response.Status.UNAUTHORIZED);

    StringBuilder sb = new StringBuilder();

    List<String> authHeader = headers.getRequestHeader(HttpHeaders.AUTHORIZATION);
    if (authHeader != null && !authHeader.isEmpty()) {
        // should HttpHeadersImpl do it ?
        String[] authValues = authHeader.get(0).split(" ");
        if (authValues.length > 0) {
            sb.append(authValues[0]);
        }
    } else {
        sb.append("Basic");
    }
    if (realmName != null) {
        sb.append(" realm=\"").append(realmName).append('"');
    }
    builder.header(HttpHeaders.WWW_AUTHENTICATE, sb.toString());

    return builder.build();
}
 
Example #21
Source File: JAXRSUtilsTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testSingletonContextFields() throws Exception {

    ClassResourceInfo cri = new ClassResourceInfo(Customer.class, true);
    Customer c = new Customer();
    cri.setResourceProvider(new SingletonResourceProvider(c));

    Message m = createMessage();
    m.put(Message.PROTOCOL_HEADERS, new HashMap<String, List<String>>());
    ServletContext servletContextMock = EasyMock.createNiceMock(ServletContext.class);
    m.put(AbstractHTTPDestination.HTTP_CONTEXT, servletContextMock);
    HttpServletRequest httpRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    m.put(AbstractHTTPDestination.HTTP_REQUEST, httpRequest);
    HttpServletResponse httpResponse = EasyMock.createMock(HttpServletResponse.class);
    m.put(AbstractHTTPDestination.HTTP_RESPONSE, httpResponse);

    InjectionUtils.injectContextProxies(cri, cri.getResourceProvider().getInstance(null));
    InjectionUtils.injectContextFields(c, cri, m);
    InjectionUtils.injectContextMethods(c, cri, m);
    assertSame(ThreadLocalUriInfo.class, c.getUriInfo2().getClass());
    assertSame(UriInfoImpl.class,
               ((ThreadLocalProxy<UriInfo>)c.getUriInfo2()).get().getClass());
    assertSame(HttpHeadersImpl.class,
               ((ThreadLocalProxy<HttpHeaders>)c.getHeaders()).get().getClass());
    assertSame(RequestImpl.class,
               ((ThreadLocalProxy<Request>)c.getRequest()).get().getClass());
    assertSame(ResourceInfoImpl.class,
               ((ThreadLocalProxy<ResourceInfo>)c.getResourceInfo()).get().getClass());
    assertSame(SecurityContextImpl.class,
               ((ThreadLocalProxy<SecurityContext>)c.getSecurityContext()).get().getClass());
    assertSame(ProvidersImpl.class,
               ((ThreadLocalProxy<Providers>)c.getBodyWorkers()).get().getClass());

    assertSame(servletContextMock,
               ((ThreadLocalProxy<ServletContext>)c.getThreadLocalServletContext()).get());
    assertSame(servletContextMock,
               ((ThreadLocalProxy<ServletContext>)c.getServletContext()).get());
    assertSame(servletContextMock,
               ((ThreadLocalProxy<ServletContext>)c.getSuperServletContext()).get());
    HttpServletRequest currentReq =
        ((ThreadLocalProxy<HttpServletRequest>)c.getServletRequest()).get();
    assertSame(httpRequest,
               ((HttpServletRequestFilter)currentReq).getRequest());
    HttpServletResponseFilter filter = (
        HttpServletResponseFilter)((ThreadLocalProxy<HttpServletResponse>)c.getServletResponse()).get();
    assertSame(httpResponse, filter.getResponse());
}
 
Example #22
Source File: MessageContextImplTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetHttpHeaders() {
    MessageContext mc = new MessageContextImpl(new MessageImpl());
    assertSame(HttpHeadersImpl.class, mc.getHttpHeaders().getClass());
    assertSame(HttpHeadersImpl.class, mc.getContext(HttpHeaders.class).getClass());
}
 
Example #23
Source File: WadlGenerator.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void doFilter(ContainerRequestContext context, Message m) {
    if (!"GET".equals(m.get(Message.HTTP_REQUEST_METHOD))) {
        return;
    }

    UriInfo ui = context.getUriInfo();
    if (!ui.getQueryParameters().containsKey(WADL_QUERY)) {
        if (stylesheetReference != null || !docLocationMap.isEmpty()) {
            String path = ui.getPath(false);
            if (path.startsWith("/") && path.length() > 0) {
                path = path.substring(1);
            }
            if (stylesheetReference != null && path.endsWith(".xsl")
                || docLocationMap.containsKey(path)) {
                context.abortWith(getExistingResource(m, ui, path));
            }
        }
        return;
    }

    if (ignoreRequests) {
        context.abortWith(Response.status(404).build());
        return;
    }

    if (whiteList != null && !whiteList.isEmpty()) {
        ServletRequest servletRequest = (ServletRequest)m.getContextualProperty(
            "HTTP.REQUEST");
        String remoteAddress = null;
        if (servletRequest != null) {
            remoteAddress = servletRequest.getRemoteAddr();
        } else {
            remoteAddress = "";
        }
        boolean foundMatch = false;
        for (String addr : whiteList) {
            if (addr.equals(remoteAddress)) {
                foundMatch = true;
                break;
            }
        }
        if (!foundMatch) {
            context.abortWith(Response.status(404).build());
            return;
        }
    }

    HttpHeaders headers = new HttpHeadersImpl(m);
    List<MediaType> accepts = headers.getAcceptableMediaTypes();
    MediaType type = accepts.contains(WADL_TYPE) ? WADL_TYPE : accepts
        .contains(MediaType.APPLICATION_JSON_TYPE) ? MediaType.APPLICATION_JSON_TYPE
            : defaultWadlResponseMediaType;

    Response response = getExistingWadl(m, ui, type);
    if (response != null) {
        context.abortWith(response);
        return;
    }

    boolean isJson = isJson(type);

    StringBuilder sbMain = generateWADL(getBaseURI(m, ui), getResourcesList(m, ui), isJson, m, ui);

    m.getExchange().put(JAXRSUtils.IGNORE_MESSAGE_WRITERS, !isJson && ignoreMessageWriters);
    Response r = Response.ok().type(type).entity(createResponseEntity(m, ui, sbMain.toString(), isJson)).build();
    context.abortWith(r);
}
 
Example #24
Source File: AbstractServiceProviderFilter.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
protected boolean checkSecurityContext(FedizContext fedConfig, Message m, MultivaluedMap<String, String> params) {
    HttpHeaders headers = new HttpHeadersImpl(m);
    Map<String, Cookie> cookies = headers.getCookies();

    Cookie securityContextCookie = cookies.get(SECURITY_CONTEXT_TOKEN);

    ResponseState responseState = getValidResponseState(securityContextCookie, fedConfig, m);
    if (responseState == null) {
        return false;
    }

    Cookie relayStateCookie = cookies.get(SECURITY_CONTEXT_STATE);
    if (fedConfig.isRequestStateValidation()) {
        if (relayStateCookie == null) {
            reportError("MISSING_RELAY_COOKIE");
            return false;
        }
        String originalRelayState = responseState.getState();
        if (!originalRelayState.equals(relayStateCookie.getValue())) {
            // perhaps the response state should also be removed
            reportError("INVALID_RELAY_STATE");
            return false;
        }

        // Check to see if a CSRF-style attack is being mounted
        String state = getState(fedConfig, params);
        if (state != null && !state.equals(responseState.getState())) {
            LOG.error("wctx parameter does not match stored value");
            throw ExceptionUtils.toForbiddenException(null, null);
        }
    }

    // Create SecurityContext
    try {
        Element token =
            StaxUtils.read(new StringReader(responseState.getAssertion())).getDocumentElement();
        setSecurityContext(responseState, m, token);
    } catch (Exception ex) {
        reportError("INVALID_RESPONSE_STATE");
        return false;
    }

    return true;
}
 
Example #25
Source File: ServerInInterceptor.java    From peer-os with Apache License 2.0 4 votes vote down vote up
/**
 * Intercepts a message. Interceptors should NOT invoke handleMessage or handleFault on the next interceptor - the
 * interceptor chain will take care of this.
 */
@Override
public void handleMessage( final Message message )
{
    try
    {
        if ( InterceptorState.SERVER_IN.isActive( message ) )
        {
            //obtain client request
            HttpServletRequest req = ( HttpServletRequest ) message.getExchange().getInMessage()
                                                                   .get( AbstractHTTPDestination.HTTP_REQUEST );

            if ( req.getLocalPort() == Common.DEFAULT_PUBLIC_SECURE_PORT )
            {
                HttpHeaders headers = new HttpHeadersImpl( message.getExchange().getInMessage() );
                String subutaiHeader = headers.getHeaderString( Common.SUBUTAI_HTTP_HEADER );

                String path = req.getRequestURI();

                if ( path.startsWith( "/rest/v1/peer" ) )
                {
                    handlePeerMessage( subutaiHeader, message );
                }
                else
                {
                    final String prefix = "/rest/v1/env";
                    if ( path.startsWith( prefix ) )
                    {
                        String s = path.substring( prefix.length() + 1 );
                        String environmentId = s.substring( 0, s.indexOf( "/" ) );
                        handleEnvironmentMessage( subutaiHeader, environmentId, message );
                    }
                }
            }
        }
    }
    catch ( Exception e )
    {
        throw new Fault( e );
    }
}