Example usage for javax.security.jacc PolicyContext registerHandler

List of usage examples for javax.security.jacc PolicyContext registerHandler

Introduction

In this page you can find the example usage for javax.security.jacc PolicyContext registerHandler.

Prototype


public static void registerHandler(String key, PolicyContextHandler handler, boolean replace)
        throws javax.security.jacc.PolicyContextException 

Source Link

Document

Authorization protected method used to register a container specific PolicyContext handler.

Usage

From source file:org.jboss.web.tomcat.tc5.Tomcat5.java

public void startService() throws Exception {

    System.setProperty("catalina.ext.dirs",
            (System.getProperty("jboss.server.home.dir") + File.separator + "lib"));

    String objectNameS = catalinaDomain + ":type=server";
    ObjectName objectName = new ObjectName(objectNameS);

    // Set the modeler Registry MBeanServer to the that of the tomcat service
    Registry.getRegistry().setMBeanServer(server);

    server.createMBean("org.apache.commons.modeler.BaseModelMBean", objectName,
            new Object[] { "org.apache.catalina.startup.Catalina" }, new String[] { "java.lang.String" });

    server.setAttribute(objectName, new Attribute("catalinaHome", System.getProperty("jboss.server.home.dir")));
    server.setAttribute(objectName, new Attribute("configFile", serverConfigFile));
    server.setAttribute(objectName, new Attribute("useNaming", new Boolean(false)));
    server.setAttribute(objectName, new Attribute("useShutdownHook", new Boolean(false)));
    server.setAttribute(objectName, new Attribute("await", new Boolean(false)));
    server.setAttribute(objectName, new Attribute("redirectStreams", new Boolean(false)));

    server.invoke(objectName, "create", new Object[] {}, new String[] {});

    server.invoke(objectName, "start", new Object[] {}, new String[] {});

    // Configure any SingleSignOn valves      

    ObjectName ssoQuery = new ObjectName("*:type=Valve,*");
    Iterator iterator = server.queryMBeans(ssoQuery, null).iterator();
    while (iterator.hasNext()) {
        ObjectName ssoObjectName = ((ObjectInstance) iterator.next()).getObjectName();
        String name = ssoObjectName.getKeyProperty("name");

        /* Ensure that the SingleSignOn valve requires that each
           request be reauthenticated to the security mgr. Should not
           be neccessary now that we cache the principal in the session.
        if ((name != null) && (name.indexOf("SingleSignOn") >= 0))
        {//from   w w w  .ja va2 s.  c om
           log.info("Turning on reauthentication of each request on " +
             ssoObjectName);
           server.setAttribute(ssoObjectName, new Attribute
              ("requireReauthentication", Boolean.TRUE));
        }
        */

        // If the valve is a ClusteredSingleSignOn and we have a shared
        // TreeCache configured, configure the valve to use the shared one
        if (cacheName != null && "ClusteredSingleSignOn".equals(name)) {
            String tcName = (String) server.getAttribute(ssoObjectName, "treeCacheName");
            tcName = (tcName != null ? tcName : DEFAULT_CACHE_NAME);
            ObjectName ssoCacheName = new ObjectName(tcName);
            // Only override if the valve's cacheName property was not
            // explicitly set in server.xml to a non-default value
            if (ssoCacheName.equals(new ObjectName(DEFAULT_CACHE_NAME))) {
                log.info("Setting the cache name to " + cacheName + " on " + ssoObjectName);
                server.setAttribute(ssoObjectName, new Attribute("treeCacheName", cacheName));
            }
        }
    }

    // Register the web container JACC PolicyContextHandlers
    HttpServletRequestPolicyContextHandler handler = new HttpServletRequestPolicyContextHandler();
    PolicyContext.registerHandler(HttpServletRequestPolicyContextHandler.WEB_REQUEST_KEY, handler, true);

    // The ServiceController used to control web app startup dependencies
    serviceController = (ServiceControllerMBean) MBeanProxyExt.create(ServiceControllerMBean.class,
            ServiceControllerMBean.OBJECT_NAME, server);

    // make a proxy to myself, so that calls from the MainDeployer
    // can go through the MBeanServer, so interceptors can be added
    thisProxy = (SubDeployerExt) MBeanProxyExt.create(SubDeployerExt.class, super.getServiceName(),
            super.getServer());

    // Register with the main deployer
    mainDeployer.addDeployer(thisProxy);

    // If we are hot-deployed *after* the overall server is started
    // we'll never receive Server.START_NOTIFICATION_TYPE, so check
    // with the Server and start the connectors immediately, if this is the case.
    // Otherwise register to receive the server start-up notification.
    Boolean started = (Boolean) server.getAttribute(ServerImplMBean.OBJECT_NAME, "Started");
    if (started.booleanValue() == true) {
        log.debug("Server '" + ServerImplMBean.OBJECT_NAME + "' already started, starting connectors now");

        startConnectors();
    } else {
        // Register for notification of the overall server startup
        log.debug("Server '" + ServerImplMBean.OBJECT_NAME
                + "' not started, registering for start-up notification");

        server.addNotificationListener(ServerImplMBean.OBJECT_NAME, this, null, null);
    }
}

From source file:test.unit.be.fedict.eid.applet.service.signer.HttpSessionTemporaryDataStorageTest.java

@Test
public void testStorage() throws Exception {
    // setup// w  w  w.j  a  va 2  s .co m
    HttpSessionTemporaryDataStorage testedInstance = new HttpSessionTemporaryDataStorage();
    byte[] data = "hello world".getBytes();

    HttpServletRequest mockHttpServletRequest = EasyMock.createMock(HttpServletRequest.class);
    PolicyContextHandler policyContextHandler = new HttpServletRequestPolicyContextHandler(
            mockHttpServletRequest);
    PolicyContext.registerHandler(HttpServletRequestPolicyContextHandler.KEY, policyContextHandler, false);

    HttpSession mockHttpSession = EasyMock.createMock(HttpSession.class);
    EasyMock.expect(mockHttpServletRequest.getSession()).andStubReturn(mockHttpSession);
    final Capture<OutputStream> tempOutputStreamCapture = new Capture<OutputStream>();
    mockHttpSession.setAttribute(EasyMock.eq(HttpSessionTemporaryDataStorage.TEMP_OUTPUT_STREAM_ATTRIBUTE),
            EasyMock.capture(tempOutputStreamCapture));
    EasyMock.expect(mockHttpSession.getAttribute(HttpSessionTemporaryDataStorage.TEMP_OUTPUT_STREAM_ATTRIBUTE))
            .andAnswer(new IAnswer<OutputStream>() {
                public OutputStream answer() throws Throwable {
                    return tempOutputStreamCapture.getValue();
                }
            });

    // prepare
    EasyMock.replay(mockHttpServletRequest, mockHttpSession);

    // operate
    OutputStream outputStream = testedInstance.getTempOutputStream();
    IOUtils.write(data, outputStream);

    InputStream inputStream = testedInstance.getTempInputStream();
    byte[] resultData = IOUtils.toByteArray(inputStream);

    // verify
    EasyMock.verify(mockHttpServletRequest, mockHttpSession);
    assertArrayEquals(data, resultData);
}

From source file:test.unit.test.be.fedict.eid.applet.model.XmlSignatureServiceBeanTest.java

@Test
public void testPreSignPostSign() throws Exception {
    // setup//from  www . j  a v a2  s  . co  m
    KeyPair keyPair = generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    X509Certificate certificate = generateCertificate(keyPair.getPublic(), "CN=Test", notBefore, notAfter, null,
            keyPair.getPrivate(), true, 0, null, new KeyUsage(KeyUsage.nonRepudiation));

    byte[] toBeSigned = "hello world".getBytes();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    byte[] digestValue = messageDigest.digest(toBeSigned);

    List<DigestInfo> digestInfos = new LinkedList<DigestInfo>();
    digestInfos.add(new DigestInfo(digestValue, "SHA-1", "test-file-name"));

    HttpServletRequest mockHttpServletRequest = EasyMock.createMock(HttpServletRequest.class);
    HttpSession mockHttpSession = EasyMock.createMock(HttpSession.class);
    EasyMock.expect(mockHttpServletRequest.getSession()).andStubReturn(mockHttpSession);
    // XML signature digest algorithm
    EasyMock.expect(mockHttpSession.getAttribute("signDigestAlgo")).andStubReturn("SHA-1");

    PolicyContextHandler handler = new PolicyContextTestHandler(mockHttpServletRequest);
    PolicyContext.registerHandler("javax.servlet.http.HttpServletRequest", handler, false);

    Capture<String> xmlDocumentCapture = new Capture<String>();
    mockHttpSession.setAttribute(EasyMock.eq("xmlDocument"), EasyMock.capture(xmlDocumentCapture));

    // prepare
    EasyMock.replay(mockHttpServletRequest, mockHttpSession);

    // operate
    DigestInfo resultDigestInfo = this.testedInstance.preSign(digestInfos, null);

    // verify
    EasyMock.verify(mockHttpServletRequest, mockHttpSession);
    assertNotNull(resultDigestInfo);
    assertNotNull(resultDigestInfo.digestValue);
    assertNotNull(resultDigestInfo.digestAlgo);
    assertNotNull(resultDigestInfo.description);
    LOG.debug("digest algo: " + resultDigestInfo.digestAlgo);
    LOG.debug("description: " + resultDigestInfo.description);

    // create the external signature
    byte[] digestInfoValue = ArrayUtils.addAll(SHA1_DIGEST_INFO_PREFIX, resultDigestInfo.digestValue);

    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate());
    byte[] signatureValue = cipher.doFinal(digestInfoValue);

    List<X509Certificate> signingCertificateChain = new LinkedList<X509Certificate>();
    signingCertificateChain.add(certificate);

    // setup
    EasyMock.reset(mockHttpServletRequest, mockHttpSession);

    EasyMock.expect(mockHttpServletRequest.getSession()).andStubReturn(mockHttpSession);
    EasyMock.expect(mockHttpSession.getAttribute("xmlDocument")).andReturn(xmlDocumentCapture.getValue());
    mockHttpSession.setAttribute(EasyMock.eq("xmlDocument"), EasyMock.capture(xmlDocumentCapture));

    // prepare
    EasyMock.replay(mockHttpServletRequest, mockHttpSession);

    // operate
    this.testedInstance.postSign(signatureValue, signingCertificateChain);

    // verify
    EasyMock.verify(mockHttpServletRequest, mockHttpSession);

    String signedDocumentStr = xmlDocumentCapture.getValue();
    StringReader stringReader = new StringReader(signedDocumentStr);
    InputSource inputSource = new InputSource(stringReader);
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document signedDocument = documentBuilder.parse(inputSource);

    Element signatureElement = (Element) XPathAPI.selectSingleNode(signedDocument, "ds:Signature");
    assertNotNull(signatureElement);

    XMLSignature apacheXmlSignature = new XMLSignature(signatureElement, null);
    ResourceTestResolver resourceResolver = new ResourceTestResolver();
    resourceResolver.addResource("test-file-name", toBeSigned);
    apacheXmlSignature.addResourceResolver(resourceResolver);
    boolean signatureResult = apacheXmlSignature.checkSignatureValue(keyPair.getPublic());
    assertTrue(signatureResult);

    LOG.debug("XML signature: " + xmlDocumentCapture.getValue());
}