Example usage for javax.xml.ws WebServiceContext getMessageContext

List of usage examples for javax.xml.ws WebServiceContext getMessageContext

Introduction

In this page you can find the example usage for javax.xml.ws WebServiceContext getMessageContext.

Prototype

public MessageContext getMessageContext();

Source Link

Document

Returns the MessageContext for the request being served at the time this method is called.

Usage

From source file:dk.statsbiblioteket.sbutil.webservices.authentication.ExtractCredentials.java

/**
 * Extract credentials from a web service context.
 *
 * @param wscontext A given web service context.
 * @return Credentials extracted from the web service context.
 * @throws CredentialsException On trouble extracting the credentials.
 * @throws NoCredentialsException If there are no credentials in the
 * context.//from  w  w w. j  a v  a 2  s.  co  m
 */
public static Credentials extract(WebServiceContext wscontext) throws CredentialsException {
    MessageContext mc = wscontext.getMessageContext();
    //FIXME: NPE on no servlet request?
    //FIXME: ClassCastException on other type of SOAP webservice call
    HttpServletRequest request = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST);
    return extract(request);
}

From source file:it.vige.greenarea.gtg.webservice.auth.LDAPauth.java

public static String doAuthentication(WebServiceContext wsContext) throws LDAPException {

    String result;//www  .jav  a  2  s. co  m
    MessageContext mctx = wsContext.getMessageContext();

    Map<String, Object> http_headers = (Map) mctx.get(MessageContext.HTTP_REQUEST_HEADERS);
    List<Object> list = (List) http_headers.get("Authorization");

    if (list == null || list.isEmpty()) {
        result = "Authentication failed! This WS needs BASIC Authentication!";
        throw new LDAPException(ResultCode.AUTH_METHOD_NOT_SUPPORTED, result);
    }

    String userpass = (String) list.get(0);
    userpass = userpass.substring(5);
    byte[] buf = Base64.decodeBase64(userpass.getBytes());// decodeBase64(userpass.getBytes());

    String credentials = StringUtils.newStringUtf8(buf);
    String username;
    String password;

    int p = credentials.indexOf(":");

    if (p > -1) {

        username = credentials.substring(0, p);

        password = credentials.substring(p + 1);

    } else {

        result = "There was an error while decoding the Authentication!";
        throw new LDAPException(ResultCode.DECODING_ERROR, result);
    }
    /*
     * Creazione di una "Identity" Se non mi serve un sottodominio, posso
     * anche usare il costruttore Identity(usr,pwd)
     */
    logger.debug("*** LOG *** username: " + username + " pwd: " + password);
    logger.debug("*** LOG *** username: " + username + " AUTHORIZED!");
    return username;
}

From source file:be.fedict.eid.idp.protocol.ws_federation.sts.WSSecuritySoapHandler.java

public static Element getToken(WebServiceContext context) {
    MessageContext messageContext = context.getMessageContext();
    Element soapElement = (Element) messageContext.get(SAML_TOKEN_CONTEXT_ATTRIBUTE);
    return soapElement;
}

From source file:it.greenvulcano.gvesb.api.security.JaxWsIdentityInfo.java

public JaxWsIdentityInfo(WebServiceContext securityContext) {
    super();/*ww w  .j a  v a2s .c o m*/

    HttpServletRequest request = (HttpServletRequest) securityContext.getMessageContext()
            .get(MessageContext.SERVLET_REQUEST);

    this.securityContext = (SecurityContext) securityContext.getMessageContext()
            .get(SecurityContext.class.getName());
    this.remoteAddress = request != null ? request.getRemoteAddr() : null;
}

From source file:org.grycap.vmrc.service.SecurityService.java

public User getUserFromContext(WebServiceContext webServiceContext) throws ServiceException {
    try {/*from   w w w.j a va2 s .c om*/
        MessageContext messageContext = webServiceContext.getMessageContext();
        Map<String, Object> httpHeaders = (Map<String, Object>) messageContext
                .get(MessageContext.HTTP_REQUEST_HEADERS);
        List<?> userList = (List<?>) httpHeaders.get("Username");
        List<?> passList = (List<?>) httpHeaders.get("Password");

        String clientUserName = (userList != null) ? userList.get(0).toString() : "anonymous";
        String clientPassword = (passList != null) ? passList.get(0).toString() : "";

        return new User(clientUserName, clientPassword);
    } catch (Exception e) {
        throw new ServiceException(e);
    }
}

From source file:org.apache.axis2.jaxws.context.utils.ContextUtils.java

private static SOAPMessageContext getSOAPMessageContext(MessageContext jaxwsMessageContext) {
    org.apache.axis2.context.MessageContext msgContext = jaxwsMessageContext.getAxisMessageContext();
    ServiceContext serviceContext = msgContext.getServiceContext();
    SOAPMessageContext soapMessageContext = null;
    if (serviceContext != null) {
        WebServiceContext wsc = (WebServiceContext) serviceContext
                .getProperty(EndpointLifecycleManagerImpl.WEBSERVICE_MESSAGE_CONTEXT);
        if (wsc != null) {
            soapMessageContext = (SOAPMessageContext) wsc.getMessageContext();
        }/*from  w  w w .  ja va2 s  . c o m*/
    }
    return soapMessageContext;
}

From source file:org.apache.juddi.v3.auth.HTTPContainerAuthenticator.java

@Override
public UddiEntityPublisher identify(String authInfoNotused, String authorizedNameNotused, WebServiceContext ctx)
        throws AuthenticationException, FatalErrorException {
    int MaxBindingsPerService = -1;
    int MaxServicesPerBusiness = -1;
    int MaxTmodels = -1;
    int MaxBusinesses = -1;
    try {//w ww .  j  a  va 2 s . c  o  m
        MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE,
                -1);
        MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS,
                -1);
        MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1);
        MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1);
    } catch (Exception ex) {
        MaxBindingsPerService = -1;
        MaxServicesPerBusiness = -1;
        MaxTmodels = -1;
        MaxBusinesses = -1;
        log.error("config exception! ", ex);
    }
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        String user = null;
        if (ctx == null)
            throw new UnknownUserException(
                    new ErrorMessage("errors.auth.NoPublisher", "no web service context!"));
        if (ctx.getUserPrincipal() != null) {
            user = ctx.getUserPrincipal().getName();
        }
        if (user == null) {
            MessageContext mc = ctx.getMessageContext();
            HttpServletRequest req = null;
            if (mc != null) {
                req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST);
            }
            if (req != null && req.getUserPrincipal() != null) {
                user = req.getUserPrincipal().getName();
            }
        }
        if (user == null || user.length() == 0) {
            throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher"));
        }
        tx.begin();
        Publisher publisher = em.find(Publisher.class, user);
        if (publisher == null) {
            log.warn("Publisher \"" + user
                    + "\" was not found in the database, adding the publisher in on the fly.");
            publisher = new Publisher();
            publisher.setAuthorizedName(user);
            publisher.setIsAdmin("false");
            publisher.setIsEnabled("true");
            publisher.setMaxBindingsPerService(MaxBindingsPerService);
            publisher.setMaxBusinesses(MaxBusinesses);
            publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness);
            publisher.setMaxTmodels(MaxTmodels);
            publisher.setPublisherName("Unknown");
            em.persist(publisher);
            tx.commit();
        }

        return publisher;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:org.apache.juddi.v3.auth.HTTPHeaderAuthenticator.java

@Override
public UddiEntityPublisher identify(String notusedauthtoken, String notusedusername, WebServiceContext ctx)
        throws AuthenticationException, FatalErrorException {
    int MaxBindingsPerService = -1;
    int MaxServicesPerBusiness = -1;
    int MaxTmodels = -1;
    int MaxBusinesses = -1;
    String http_header_name = null;
    try {//from  w  w  w  .ja  v a 2s .c om
        http_header_name = AppConfig.getConfiguration()
                .getString(Property.JUDDI_AUTHENTICATOR_HTTP_HEADER_NAME);
        MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE,
                -1);
        MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS,
                -1);
        MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1);
        MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1);
    } catch (Exception ex) {
        MaxBindingsPerService = -1;
        MaxServicesPerBusiness = -1;
        MaxTmodels = -1;
        MaxBusinesses = -1;
        log.error("config exception! ", ex);
    }
    if (http_header_name == null) {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", "misconfiguration!"));
    }
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        String user = null;

        MessageContext mc = ctx.getMessageContext();
        HttpServletRequest req = null;
        if (mc != null) {
            req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST);
            user = req.getHeader(http_header_name);
        }

        if (user == null || user.length() == 0) {
            throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher"));
        }
        tx.begin();
        Publisher publisher = em.find(Publisher.class, user);
        if (publisher == null) {
            log.warn("Publisher \"" + user
                    + "\" was not found in the database, adding the publisher in on the fly.");
            publisher = new Publisher();
            publisher.setAuthorizedName(user);
            publisher.setIsAdmin("false");
            publisher.setIsEnabled("true");
            publisher.setMaxBindingsPerService(MaxBindingsPerService);
            publisher.setMaxBusinesses(MaxBusinesses);
            publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness);
            publisher.setMaxTmodels(MaxTmodels);
            publisher.setPublisherName("Unknown");
            em.persist(publisher);
            tx.commit();
        }

        return publisher;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:test.unit.be.fedict.eid.idp.protocol.ws_federation.sts.SecurityTokenServicePortImplTest.java

@Test
public void testValidation() throws Exception {
    // setup/*  ww  w .j  a va  2 s .  c o  m*/
    InputStream requestInputStream = SecurityTokenServicePortImplTest.class
            .getResourceAsStream("/sts-validation-request.xml");
    assertNotNull(requestInputStream);

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.parse(requestInputStream);

    Element requestSecurityTokenElement = (Element) document
            .getElementsByTagNameNS("http://docs.oasis-open.org/ws-sx/ws-trust/200512", "RequestSecurityToken")
            .item(0);

    Element x509Certificate = (Element) document
            .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "X509Certificate").item(0);
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(
            new ByteArrayInputStream(Base64.decodeBase64(x509Certificate.getFirstChild().getNodeValue())));
    List<X509Certificate> certificateChain = Collections.singletonList(certificate);

    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class,
            be.fedict.eid.idp.wstrust.jaxb.wspolicy.ObjectFactory.class,
            be.fedict.eid.idp.wstrust.jaxb.wsaddr.ObjectFactory.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

    JAXBElement<RequestSecurityTokenType> resultElement = (JAXBElement<RequestSecurityTokenType>) unmarshaller
            .unmarshal(requestSecurityTokenElement);
    RequestSecurityTokenType requestSecurityToken = resultElement.getValue();

    SecurityTokenServicePortImpl testedInstance = new SecurityTokenServicePortImpl();

    WebServiceContext mockWebServiceContext = EasyMock.createMock(WebServiceContext.class);
    injectResource(mockWebServiceContext, testedInstance);

    MessageContext mockMessageContext = EasyMock.createMock(MessageContext.class);

    EasyMock.expect(mockWebServiceContext.getMessageContext()).andStubReturn(mockMessageContext);

    ServletContext mockServletContext = EasyMock.createMock(ServletContext.class);

    EasyMock.expect(mockMessageContext.get(MessageContext.SERVLET_CONTEXT)).andReturn(mockServletContext);

    IdentityProviderConfiguration mockIdentityProviderConfiguration = EasyMock
            .createMock(IdentityProviderConfiguration.class);

    EasyMock.expect(mockServletContext.getAttribute(
            IdentityProviderConfigurationFactory.IDENTITY_PROVIDER_CONFIGURATION_CONTEXT_ATTRIBUTE))
            .andReturn(mockIdentityProviderConfiguration);

    EasyMock.expect(mockIdentityProviderConfiguration.getIdentityCertificateChain())
            .andReturn(certificateChain);

    EasyMock.expect(mockIdentityProviderConfiguration.getDefaultIssuer()).andReturn("e-contract-2012");

    Element samlElement = (Element) document
            .getElementsByTagNameNS(WSTrustConstants.SAML2_NAMESPACE, "Assertion").item(0);
    EasyMock.expect(mockMessageContext.get(WSSecuritySoapHandler.class.getName() + ".samlToken"))
            .andStubReturn(samlElement);

    // prepare
    EasyMock.replay(mockWebServiceContext, mockMessageContext, mockServletContext,
            mockIdentityProviderConfiguration);

    // operate
    RequestSecurityTokenResponseCollectionType result = testedInstance
            .requestSecurityToken(requestSecurityToken);

    // verify
    EasyMock.verify(mockWebServiceContext, mockMessageContext, mockServletContext,
            mockIdentityProviderConfiguration);
    assertNotNull(result);

    List<RequestSecurityTokenResponseType> resultList = result.getRequestSecurityTokenResponse();
    assertEquals(1, resultList.size());
    RequestSecurityTokenResponseType requestSecurityTokenResponse = resultList.get(0);
    List<Object> responseObjects = requestSecurityTokenResponse.getAny();
    boolean valid = false;
    String reason = null;
    for (Object responseObject : responseObjects) {
        LOG.debug("response object type: " + responseObject);
        if (responseObject instanceof JAXBElement) {
            JAXBElement jaxbElement = (JAXBElement) responseObject;
            QName qname = jaxbElement.getName();
            LOG.debug("qname: " + qname);
            if (new QName(WSTrustConstants.WS_TRUST_NAMESPACE, "Status").equals(qname)) {
                StatusType status = (StatusType) jaxbElement.getValue();
                String code = status.getCode();
                LOG.debug("status code: " + code);
                if (WSTrustConstants.VALID_STATUS_CODE.equals(code)) {
                    valid = true;
                }
                reason = status.getReason();
            }
        }
    }
    LOG.debug("status reason: " + reason);
    assertTrue(reason.indexOf("policy") != -1);
}