Java Code Examples for org.apache.cxf.jaxrs.utils.JAXRSUtils#getCurrentMessage()

The following examples show how to use org.apache.cxf.jaxrs.utils.JAXRSUtils#getCurrentMessage() . 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: BookStore.java    From cxf with Apache License 2.0 6 votes vote down vote up
private String getRecipientText(JweJsonConsumer consumer, String recipientPropLoc, String recipientKid) { 
    Message message = JAXRSUtils.getCurrentMessage();
    
    
    Properties recipientProps = JweUtils.loadJweProperties(message, recipientPropLoc);
    JsonWebKey recipientKey = JwkUtils.loadJwkSet(message, recipientProps, null).getKey(recipientKid);
    
    ContentAlgorithm contentEncryptionAlgorithm = JweUtils.getContentEncryptionAlgorithm(recipientProps);
    
    JweDecryptionProvider jweRecipient = 
        JweUtils.createJweDecryptionProvider(recipientKey, contentEncryptionAlgorithm);
    
    JweDecryptionOutput jweRecipientOutput = 
        consumer.decryptWith(jweRecipient,
                             Collections.singletonMap("kid", recipientKid));
    return jweRecipientOutput.getContentText();
}
 
Example 2
Source File: AbstractJweJsonWriterProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected List<String> getPropertyLocations() {
    Message m = JAXRSUtils.getCurrentMessage();
    Object propLocsProp =
        MessageUtils.getContextualProperty(m, JoseConstants.RSSEC_ENCRYPTION_OUT_PROPS,
                                           JoseConstants.RSSEC_ENCRYPTION_PROPS);
    if (propLocsProp == null) {
        if (encProviders == null) {
            LOG.warning("JWE JSON init properties resource is not identified");
            throw new JweException(JweException.Error.NO_INIT_PROPERTIES);
        }
        return Collections.emptyList();
    }
    List<String> propLocs = null;
    if (propLocsProp instanceof String) {
        String[] props = ((String)propLocsProp).split(",");
        propLocs = Arrays.asList(props);
    } else {
        propLocs = CastUtils.cast((List<?>)propLocsProp);
    }
    return propLocs;
}
 
Example 3
Source File: CrossOriginResourceSharingFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) {
    Message m = JAXRSUtils.getCurrentMessage();

    String httpMethod = (String)m.get(Message.HTTP_REQUEST_METHOD);
    if (HttpMethod.OPTIONS.equals(httpMethod)) {
        Response r = preflightRequest(m);
        if (r != null) {
            context.abortWith(r);
        }
    } else if (findResourceMethod) {
        Method method = getResourceMethod(m, httpMethod);
        simpleRequest(m, method);
    } else {
        m.getInterceptorChain().add(new CorsInInterceptor());
    }

}
 
Example 4
Source File: SamlHeaderInHandler.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) {
    Message message = JAXRSUtils.getCurrentMessage();

    List<String> values = headers.getRequestHeader(HttpHeaders.AUTHORIZATION);
    if (values == null || values.size() != 1 || !values.get(0).startsWith(SAML_AUTH)) {
        throwFault("Authorization header must be available and use SAML profile", null);
    }

    String[] parts = values.get(0).split(" ");
    if (parts.length != 2) {
        throwFault("Authorization header is malformed", null);
    }

    handleToken(message, parts[1]);
}
 
Example 5
Source File: WSS4JBasicAuthFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void filter(ContainerRequestContext requestContext) throws IOException {
    if (requestContext.getUriInfo().getPath().contains(WellKnownService.WELL_KNOWN_PATH)) {
        return;
    }

    Message message = JAXRSUtils.getCurrentMessage();
    AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);

    if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
        requestContext.abortWith(
            Response.status(401).header("WWW-Authenticate", "Basic realm=\"IdP\"").build());
        return;
    }

    try {
        super.validate(message);
    } catch (Exception ex) {
        throw ExceptionUtils.toInternalServerErrorException(ex, null);
    }
}
 
Example 6
Source File: XmlStreamReaderProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void filter(ContainerRequestContext c) throws IOException {
    String method = context.get(Message.HTTP_REQUEST_METHOD).toString();

    if ("PUT".equals(method)) {
        MultivaluedMap<String, String> map = context.getUriInfo().getPathParameters();
        if (!"123".equals(map.getFirst("id"))) {
            throw new RuntimeException();
        }
        Message m = JAXRSUtils.getCurrentMessage();
        XMLStreamReader reader =
            StaxUtils.createXMLStreamReader(m.getContent(InputStream.class));
        m.setContent(XMLStreamReader.class,
                                                  new CustomXmlStreamReader(reader));
    }
}
 
Example 7
Source File: XmlStreamWriterProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void filter(ContainerRequestContext reqC, ContainerResponseContext respC) throws IOException {
    Message m = JAXRSUtils.getCurrentMessage();
    OperationResourceInfo ori = m.getExchange().get(OperationResourceInfo.class);
    String method = ori.getHttpMethod();
    if ("PUT".equals(method)) {
        XMLStreamWriter writer =
            StaxUtils.createXMLStreamWriter(m.getContent(OutputStream.class));
        m.setContent(XMLStreamWriter.class, new CustomXmlStreamWriter(writer));
    }
}
 
Example 8
Source File: AbstractJwsJsonWriterProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected List<JwsSignatureProvider> getInitializedSigProviders(
    List<String> propLocs, List<JwsHeaders> protectedHeaders) {
    if (sigProviders != null) {
        return sigProviders;
    }
    Message m = JAXRSUtils.getCurrentMessage();
    List<JwsSignatureProvider> theSigProviders = new LinkedList<>();
    for (int i = 0; i < propLocs.size(); i++) {
        Properties props = JwsUtils.loadJwsProperties(m, propLocs.get(i));
        theSigProviders.add(JwsUtils.loadSignatureProvider(props, protectedHeaders.get(i)));
    }
    return theSigProviders;
}
 
Example 9
Source File: AttachmentUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void addMultipartOutFilter(MultipartOutputFilter filter) {
    Message m = JAXRSUtils.getCurrentMessage();
    List<MultipartOutputFilter> outFilters = CastUtils.cast((List<?>)m.get(OUT_FILTERS));
    if (outFilters == null) {
        outFilters = new ArrayList<>();
        m.put(OUT_FILTERS, outFilters);
    }
    outFilters.add(filter);
}
 
Example 10
Source File: CreateSignatureInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void sign(WriterInterceptorContext writerInterceptorContext) {
    Message m = JAXRSUtils.getCurrentMessage();
    String method = "";
    String path = "";
    // We don't pass the HTTP method + URI for the response case
    if (MessageUtils.isRequestor(m)) {
        method = HttpUtils.getProtocolHeader(JAXRSUtils.getCurrentMessage(),
                                             Message.HTTP_REQUEST_METHOD, "");
        path = uriInfo.getRequestUri().getPath();
    }

    performSignature(writerInterceptorContext.getHeaders(), path, method);
}
 
Example 11
Source File: WadlGenerator.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) {
    Message m = JAXRSUtils.getCurrentMessage();
    if (m == null) {
        return;
    }
    doFilter(context, m);
}
 
Example 12
Source File: MessageContextImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Message getCurrentMessage() {
    Message currentMessage = JAXRSUtils.getCurrentMessage();
    if (currentMessage == null) {
        currentMessage = m;
    }
    return currentMessage;
}
 
Example 13
Source File: Saml2BearerAuthHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) {
    Message message = JAXRSUtils.getCurrentMessage();
    Form form = readFormData(message);
    MultivaluedMap<String, String> formData = form.asMap();
    String assertionType = formData.getFirst(Constants.CLIENT_AUTH_ASSERTION_TYPE);
    String decodedAssertionType = assertionType != null ? HttpUtils.urlDecode(assertionType) : null;
    if (decodedAssertionType == null || !Constants.CLIENT_AUTH_SAML2_BEARER.equals(decodedAssertionType)) {
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }
    String assertion = formData.getFirst(Constants.CLIENT_AUTH_ASSERTION_PARAM);

    Element token = readToken(message, assertion);
    String clientId = formData.getFirst(OAuthConstants.CLIENT_ID);
    validateToken(message, token, clientId);


    formData.remove(OAuthConstants.CLIENT_ID);
    formData.remove(Constants.CLIENT_AUTH_ASSERTION_PARAM);
    formData.remove(Constants.CLIENT_AUTH_ASSERTION_TYPE);

    // restore input stream
    try {
        FormUtils.restoreForm(provider, form, message);
    } catch (Exception ex) {
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }
}
 
Example 14
Source File: SamlFormInHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) {
    Message message = JAXRSUtils.getCurrentMessage();

    Form form = readFormData(message);
    MultivaluedMap<String, String> formData = form.asMap();
    String assertion = formData.getFirst(SAML_ELEMENT);

    handleToken(message, assertion);

    // redirect if needed
    String samlRequestURI = formData.getFirst(SAML_RELAY_STATE);
    if (samlRequestURI != null) {
        // RelayState may actually represent a reference to a transient local state
        // containing the actual REQUEST URI client was using before being redirected
        // back to IDP - at the moment assume it's URI
        UriInfoImpl ui = new UriInfoImpl(message);
        if (!samlRequestURI.startsWith(ui.getBaseUri().toString())) {
            context.abortWith(Response.status(302).location(URI.create(samlRequestURI)).build());
            return;
        }
    }
    formData.remove(SAML_ELEMENT);
    formData.remove(SAML_RELAY_STATE);

    // restore input stream
    try {
        FormUtils.restoreForm(provider, form, message);
    } catch (Exception ex) {
        throwFault(ex.getMessage(), ex);
    }
}
 
Example 15
Source File: OAuthUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static UserSubject createSubject(SecurityContext securityContext) {
    List<String> roleNames = Collections.emptyList();
    if (securityContext instanceof LoginSecurityContext) {
        roleNames = ((LoginSecurityContext) securityContext).getUserRoles().stream().map(Principal::getName)
            .collect(toList());
    }
    UserSubject subject = new UserSubject(securityContext.getUserPrincipal().getName(), roleNames);
    Message m = JAXRSUtils.getCurrentMessage();
    if (m != null && m.get(AuthenticationMethod.class) != null) {
        subject.setAuthenticationMethod(m.get(AuthenticationMethod.class));
    }
    return subject;
}
 
Example 16
Source File: DOM4JProvider.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected Message getCurrentMessage() {
    return JAXRSUtils.getCurrentMessage();
}
 
Example 17
Source File: ThreadLocalProviders.java    From cxf with Apache License 2.0 4 votes vote down vote up
private Providers getProvidersImpl() {
    Message m = JAXRSUtils.getCurrentMessage();
    return m != null ? new ProvidersImpl(JAXRSUtils.getContextMessage(m)) : null;
}
 
Example 18
Source File: JwtBearerAuthHandler.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) {
    Message message = JAXRSUtils.getCurrentMessage();
    Form form = readFormData(message);
    MultivaluedMap<String, String> formData = form.asMap();
    String assertionType = formData.getFirst(Constants.CLIENT_AUTH_ASSERTION_TYPE);
    String decodedAssertionType = assertionType != null ? HttpUtils.urlDecode(assertionType) : null;
    if (decodedAssertionType == null || !Constants.CLIENT_AUTH_JWT_BEARER.equals(decodedAssertionType)) {
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }

    String assertion = formData.getFirst(Constants.CLIENT_AUTH_ASSERTION_PARAM);
    if (assertion == null) {
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }

    String clientId = formData.getFirst(OAuthConstants.CLIENT_ID);

    Client client = null;
    if (clientId != null && clientProvider != null) {
        client = clientProvider.getClient(clientId);
        if (client == null) {
            throw ExceptionUtils.toNotAuthorizedException(null, null);
        }
        message.put(Client.class, client);
    }
    JwtToken token = super.getJwtToken(assertion, client);

    String subjectName = (String)token.getClaim(JwtConstants.CLAIM_SUBJECT);
    if (clientId != null && !clientId.equals(subjectName)) {
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }
    message.put(OAuthConstants.CLIENT_ID, subjectName);

    formData.remove(OAuthConstants.CLIENT_ID);
    formData.remove(Constants.CLIENT_AUTH_ASSERTION_PARAM);
    formData.remove(Constants.CLIENT_AUTH_ASSERTION_TYPE);

    SecurityContext securityContext = configureSecurityContext(token);
    if (securityContext != null) {
        JAXRSUtils.getCurrentMessage().put(SecurityContext.class, securityContext);
    }

    // restore input stream
    try {
        FormUtils.restoreForm(provider, form, message);
    } catch (Exception ex) {
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }
}
 
Example 19
Source File: AuthorizationFilter.java    From iaf with Apache License 2.0 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
	if(requestContext.getMethod().equalsIgnoreCase("OPTIONS")) {
		//Preflight in here?
		return;
	}

	Message message = JAXRSUtils.getCurrentMessage();
	Method method = (Method)message.get("org.apache.cxf.resource.method");
	if(method == null) {
		log.error("Unable to fetch method from CXF Message");
		requestContext.abortWith(SERVER_ERROR);
	}

	if(method.isAnnotationPresent(DenyAll.class)) {
		//Functionality has been disallowed.
		requestContext.abortWith(FORBIDDEN);
		return;
	}
	if(method.isAnnotationPresent(PermitAll.class)) {
		//No authorization required.
		return;
	}

	//Presume `PermitAll` when RolesAllowed annotation is not set
	if(method.isAnnotationPresent(RolesAllowed.class)) {
		SecurityContext securityContext = requestContext.getSecurityContext();

		if(securityContext.getUserPrincipal() == null) {
			if(!login(requestContext)) { //Not logged in. Manually trying to authenticate the user
				requestContext.abortWith(UNAUTHORIZED);
				return;
			} else {
				System.out.println("manually logged in user [" + securityContext.getUserPrincipal().getName()+"]");
			}
		}

		RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class);
		Set<String> rolesSet = new HashSet<String>(Arrays.asList(rolesAnnotation.value()));
		System.out.println("Checking authentication for user ["+securityContext.getUserPrincipal().getName()+"] uri ["+method.getAnnotation(javax.ws.rs.Path.class).value()+"] roles " + rolesSet.toString());

		//Verifying username and password
		if(!doAuth(securityContext, rolesSet)) {
			requestContext.abortWith(FORBIDDEN);
			return;
		}
	}
}
 
Example 20
Source File: XmlSigInHandler.java    From cxf with Apache License 2.0 3 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) {
    Message message = JAXRSUtils.getCurrentMessage();

    checkSignature(message);

}