Example usage for javax.security.auth Subject Subject

List of usage examples for javax.security.auth Subject Subject

Introduction

In this page you can find the example usage for javax.security.auth Subject Subject.

Prototype

public Subject() 

Source Link

Document

Create an instance of a Subject with an empty Set of Principals and empty Sets of public and private credentials.

Usage

From source file:org.apache.zeppelin.realm.kerberos.KerberosRealm.java

/**
 * Initializes the KerberosRealm by 'kinit'ing using principal and keytab.
 * <p>//from  www.ja  va  2  s .  c om
 * It creates a Kerberos context using the principal and keytab specified in
 * the Shiro configuration.
 * <p>
 * This method should be called only once.
 *
 * @throws RuntimeException thrown if the handler could not be initialized.
 */
@Override
protected void onInit() {
    super.onInit();
    config = getConfiguration();
    try {
        if (principal == null || principal.trim().length() == 0) {
            throw new RuntimeException("Principal not defined in configuration");
        }

        if (keytab == null || keytab.trim().length() == 0) {
            throw new RuntimeException("Keytab not defined in configuration");
        }

        File keytabFile = new File(keytab);
        if (!keytabFile.exists()) {
            throw new RuntimeException("Keytab file does not exist: " + keytab);
        }

        // use all SPNEGO principals in the keytab if a principal isn't
        // specifically configured
        final String[] spnegoPrincipals;
        if (principal.equals("*")) {
            spnegoPrincipals = KerberosUtil.getPrincipalNames(keytab, Pattern.compile("HTTP/.*"));
            if (spnegoPrincipals.length == 0) {
                throw new RuntimeException("Principals do not exist in the keytab");
            }
        } else {
            spnegoPrincipals = new String[] { principal };
        }
        KeyTab keytabInstance = KeyTab.getInstance(keytabFile);

        serverSubject = new Subject();
        serverSubject.getPrivateCredentials().add(keytabInstance);
        for (String spnegoPrincipal : spnegoPrincipals) {
            Principal krbPrincipal = new KerberosPrincipal(spnegoPrincipal);
            LOG.info("Using keytab {}, for principal {}", keytab, krbPrincipal);
            serverSubject.getPrincipals().add(krbPrincipal);
        }

        if (nameRules == null || nameRules.trim().length() == 0) {
            LOG.warn("No auth_to_local rules defined, DEFAULT will be used.");
            nameRules = "DEFAULT";
        }

        KerberosName.setRules(nameRules);

        if (null == gssManager) {
            try {
                gssManager = Subject.doAs(serverSubject, new PrivilegedExceptionAction<GSSManager>() {
                    @Override
                    public GSSManager run() {
                        return GSSManager.getInstance();
                    }
                });
                LOG.trace("SPNEGO gssManager initialized.");
            } catch (PrivilegedActionException ex) {
                throw ex.getException();
            }
        }

        if (null == signer) {
            initializeSecretProvider();
        }

        Configuration hadoopConfig = new Configuration();
        hadoopGroups = new Groups(hadoopConfig);

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.betaconceptframework.astroboa.test.engine.security.CmsLoginTest.java

@Test
public void testAuthorizedRepositoriesAreTheSameFoundInSubject() {

    Subject subject = new Subject();

    String identity = "testuser";
    subject.getPrincipals().add(new IdentityPrincipal(identity));

    Group group = new CmsGroup(AstroboaPrincipalName.AuthorizedRepositories.toString());
    group.addMember(new CmsPrincipal("testRepositoryA"));
    group.addMember(new CmsPrincipal("testRepositoryB"));
    group.addMember(new CmsPrincipal(TestConstants.TEST_REPOSITORY_ID));

    subject.getPrincipals().add(group);//from  w w  w.  j av a  2 s  . c  o m

    repositoryService.login(TestConstants.TEST_REPOSITORY_ID, subject, null);

    SecurityContext securityContext = AstroboaClientContextHolder.getActiveSecurityContext();

    Assert.assertNotNull(securityContext, "Found no security context in Thread for logged in user " + identity);

    List<String> authorizedRepositories = securityContext.getAuthorizedRepositories();

    Assert.assertTrue(CollectionUtils.isNotEmpty(authorizedRepositories),
            "Authorized repositories must not be empty");

    Assert.assertTrue(authorizedRepositories.size() == 3,
            "Authorized repositories must be exactly 3. " + authorizedRepositories.toString());

    for (String repositoryId : authorizedRepositories) {
        Assert.assertTrue(
                repositoryId.equals("testRepositoryA") || repositoryId.equals("testRepositoryB")
                        || repositoryId.equals(TestConstants.TEST_REPOSITORY_ID),
                "Repository id " + repositoryId + " must not exist in authorized repositories "
                        + authorizedRepositories.toString());
    }

}

From source file:org.betaconceptframework.astroboa.test.engine.service.RepositoryServiceTest.java

@Test
public void testLoginPermanentKey() {

    String permanentKey = "fakeKey";

    //Connect to test repository with fake key
    try {//ww  w.  j ava 2s .c  o  m
        authenticationToken = repositoryService.login(TestConstants.TEST_REPOSITORY_ID,
                new AstroboaCredentials(TestConstants.TEST_USER_NAME, "betaconcept".toCharArray()),
                permanentKey);

        Assert.assertEquals(1, 2, "Login succeded with false key");
    } catch (Exception e) {
        Assert.assertEquals(e.getMessage(),
                "Invalid permanent key " + permanentKey + " for user " + TestConstants.TEST_USER_NAME
                        + " in repository " + TestConstants.TEST_REPOSITORY_ID,
                "Login did not take place with false key nevertheless exception is thrown " + e.getMessage());
    }

    //Connect with correct key
    permanentKey = "keyForTest";
    try {
        authenticationToken = repositoryService.login(TestConstants.TEST_REPOSITORY_ID,
                new AstroboaCredentials(TestConstants.TEST_USER_NAME, "betaconcept".toCharArray()),
                permanentKey);

        //Connect again and check that authentication token is the same
        String authenticationToken2 = repositoryService.login(TestConstants.TEST_REPOSITORY_ID,
                new AstroboaCredentials(TestConstants.TEST_USER_NAME, "betaconcept".toCharArray()),
                permanentKey);

        Assert.assertEquals(authenticationToken, authenticationToken2,
                "Login with trusted keys produced two different authentication tokens");

    } catch (Exception e) {
        throw new CmsException(e);
    }

    //Connect with anonymous using subject
    permanentKey = "specialKey";
    try {

        Subject subject = new Subject();
        subject.getPrincipals().add(new IdentityPrincipal("anonymous"));

        authenticationToken = repositoryService.login(TestConstants.TEST_REPOSITORY_ID, subject, permanentKey);

        //Connect again and check that authentication token is the same
        String authenticationToken2 = repositoryService.login(TestConstants.TEST_REPOSITORY_ID, subject,
                permanentKey);

        Assert.assertEquals(authenticationToken, authenticationToken2,
                "Login with trusted keys produced two different authentication tokens");

    } catch (Exception e) {
        throw new CmsException(e);
    }

    //Connect with * using subject
    permanentKey = "globalKey";
    try {

        Subject subject = new Subject();
        subject.getPrincipals().add(new IdentityPrincipal("anyUser"));

        authenticationToken = repositoryService.login(TestConstants.TEST_REPOSITORY_ID, subject, permanentKey);

        //Connect again and check that authentication token is the same
        String authenticationToken2 = repositoryService.login(TestConstants.TEST_REPOSITORY_ID, subject,
                permanentKey);

        Assert.assertEquals(authenticationToken, authenticationToken2,
                "Login with trusted keys produced two different authentication tokens");

    } catch (Exception e) {
        throw new CmsException(e);
    }

    //Back to normal
    loginToTestRepositoryAsTestUser();
    cmsRepositoryEntityFactory = CmsRepositoryEntityFactoryForActiveClient.INSTANCE.getFactory();

}

From source file:org.apache.camel.component.cxf.DefaultCxfBinding.java

/**
 * This method is called by {@link CxfConsumer}.
 *///ww  w  .  ja  v a  2s  .c om
public void populateExchangeFromCxfRequest(org.apache.cxf.message.Exchange cxfExchange,
        Exchange camelExchange) {

    Method method = null;
    QName operationName = null;
    ExchangePattern mep = ExchangePattern.InOut;

    // extract binding operation information
    BindingOperationInfo boi = camelExchange.getProperty(BindingOperationInfo.class.getName(),
            BindingOperationInfo.class);
    if (boi != null) {
        Service service = (Service) cxfExchange.get(Service.class);
        if (service != null) {
            MethodDispatcher md = (MethodDispatcher) service.get(MethodDispatcher.class.getName());
            if (md != null) {
                method = md.getMethod(boi);
            }
        }

        if (boi.getOperationInfo().isOneWay()) {
            mep = ExchangePattern.InOnly;
        }

        operationName = boi.getName();
    }

    // set operation name in header
    if (operationName != null) {
        camelExchange.getIn().setHeader(CxfConstants.OPERATION_NAMESPACE, boi.getName().getNamespaceURI());
        camelExchange.getIn().setHeader(CxfConstants.OPERATION_NAME, boi.getName().getLocalPart());
        if (LOG.isTraceEnabled()) {
            LOG.trace("Set IN header: " + CxfConstants.OPERATION_NAMESPACE + "="
                    + boi.getName().getNamespaceURI());
            LOG.trace("Set IN header: " + CxfConstants.OPERATION_NAME + "=" + boi.getName().getLocalPart());
        }
    } else if (method != null) {
        camelExchange.getIn().setHeader(CxfConstants.OPERATION_NAME, method.getName());
        if (LOG.isTraceEnabled()) {
            LOG.trace("Set IN header: " + CxfConstants.OPERATION_NAME + "=" + method.getName());
        }
    }

    // set message exchange pattern
    camelExchange.setPattern(mep);
    if (LOG.isTraceEnabled()) {
        LOG.trace("Set exchange MEP: " + mep);
    }

    // propagate headers
    Message cxfMessage = cxfExchange.getInMessage();
    propagateHeadersFromCxfToCamel(cxfMessage, camelExchange.getIn(), camelExchange);

    // propagate the security subject from CXF security context
    SecurityContext securityContext = cxfMessage.get(SecurityContext.class);
    if (securityContext != null && securityContext.getUserPrincipal() != null) {
        Subject subject = new Subject();
        subject.getPrincipals().add(securityContext.getUserPrincipal());
        camelExchange.getIn().getHeaders().put(Exchange.AUTHENTICATION, subject);
    }

    // Propagating properties from CXF Exchange to Camel Exchange has an  
    // side effect of copying reply side stuff when the producer is retried.
    // So, we do not want to do this.
    //camelExchange.getProperties().putAll(cxfExchange);

    // propagate request context
    Object value = cxfMessage.get(Client.REQUEST_CONTEXT);
    if (value != null && !headerFilterStrategy.applyFilterToExternalHeaders(Client.REQUEST_CONTEXT, value,
            camelExchange)) {
        camelExchange.getIn().setHeader(Client.REQUEST_CONTEXT, value);
        if (LOG.isTraceEnabled()) {
            LOG.trace("Populate context from CXF message " + Client.REQUEST_CONTEXT + " value=" + value);
        }
    }

    // set body
    Object body = DefaultCxfBinding.getContentFromCxf(cxfMessage,
            camelExchange.getProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.class));
    if (body != null) {
        camelExchange.getIn().setBody(body);
    }

    // propagate attachments
    if (cxfMessage.getAttachments() != null) {
        for (Attachment attachment : cxfMessage.getAttachments()) {
            camelExchange.getIn().addAttachment(attachment.getId(), attachment.getDataHandler());
        }
    }
}

From source file:org.apache.karaf.jaas.modules.ldap.LdapLoginModuleTest.java

@Test
public void testBadPassword() throws Exception {
    Properties options = ldapLoginModuleOptions();
    LDAPLoginModule module = new LDAPLoginModule();
    CallbackHandler cb = new CallbackHandler() {
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback cb : callbacks) {
                if (cb instanceof NameCallback) {
                    ((NameCallback) cb).setName("admin");
                } else if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword("blahblah".toCharArray());
                }/*from   ww w  . j av a2 s. c o  m*/
            }
        }
    };
    Subject subject = new Subject();
    module.initialize(subject, cb, null, options);

    assertEquals("Precondition", 0, subject.getPrincipals().size());
    try {
        module.login();
        fail("Should have thrown LoginException");
    } catch (LoginException e) {
        assertTrue(e.getMessage().startsWith("Authentication failed"));
    }
}

From source file:org.apache.karaf.jaas.modules.krb5.Krb5LoginModuleTest.java

@Test
public void testLoginSuccess() throws Exception {
    CallbackHandler cb = new CallbackHandler() {
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback cb : callbacks) {
                if (cb instanceof NameCallback) {
                    ((NameCallback) cb).setName("hnelson");
                } else if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword("secret".toCharArray());
                }/*ww  w. java  2s.  c  o  m*/
            }
        }
    };
    Subject subject = new Subject();

    Krb5LoginModule module = new Krb5LoginModule();
    module.initialize(subject, cb, null, new HashMap<>());

    assertEquals("Precondition", 0, subject.getPrincipals().size());

    Assert.assertTrue(module.login());
    Assert.assertTrue(module.commit());

    assertEquals(1, subject.getPrincipals().size());

    boolean foundUser = false;
    for (Principal pr : subject.getPrincipals()) {
        if (pr instanceof KerberosPrincipal) {
            assertEquals("hnelson@EXAMPLE.COM", pr.getName());
            foundUser = true;
            break;
        }
    }
    assertTrue(foundUser);

    boolean foundToken = false;
    for (Object crd : subject.getPrivateCredentials()) {
        if (crd instanceof KerberosTicket) {
            assertEquals("hnelson@EXAMPLE.COM", ((KerberosTicket) crd).getClient().getName());
            assertEquals("krbtgt/EXAMPLE.COM@EXAMPLE.COM", ((KerberosTicket) crd).getServer().getName());
            foundToken = true;
            break;
        }
    }
    assertTrue(foundToken);

    Assert.assertTrue(module.logout());

}

From source file:org.apache.catalina.security.SecurityUtil.java

/**
 * Perform work as a particular </code>Subject</code>. Here the work
 * will be granted to a <code>null</code> subject. 
 *
 * @param methodName the method to apply the security restriction
 * @param targetObject the <code>Servlet</code> on which the method will
 * be called.//w  w w. ja  v  a 2  s .co  m
 * @param targetType <code>Class</code> array used to instanciate a 
 * <code>Method</code> object.
 * @param targetArgumentst <code>Object</code> array contains the 
 * runtime parameters instance.
 * @param principal the <code>Principal</code> to which the security 
 * privilege apply..
 */
private static void execute(final Method method, final Object targetObject, final Object[] targetArguments,
        Principal principal) throws java.lang.Exception {

    try {
        Subject subject = null;
        PrivilegedExceptionAction pea = new PrivilegedExceptionAction() {
            public Object run() throws Exception {
                method.invoke(targetObject, targetArguments);
                return null;
            }
        };

        // The first argument is always the request object
        if (targetArguments != null && targetArguments[0] instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) targetArguments[0];

            HttpSession session = request.getSession(false);
            if (session != null) {
                subject = (Subject) session.getAttribute(Globals.SUBJECT_ATTR);

                if (subject == null) {
                    subject = new Subject();
                    session.setAttribute(Globals.SUBJECT_ATTR, subject);
                }
            }
        }

        Subject.doAsPrivileged(subject, pea, null);
    } catch (PrivilegedActionException pe) {
        Throwable e = ((InvocationTargetException) pe.getException()).getTargetException();

        if (log.isDebugEnabled()) {
            log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e);
        }

        if (e instanceof UnavailableException)
            throw (UnavailableException) e;
        else if (e instanceof ServletException)
            throw (ServletException) e;
        else if (e instanceof IOException)
            throw (IOException) e;
        else if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        else
            throw new ServletException(e.getMessage(), e);
    }
}

From source file:org.apache.ranger.storm.client.StormClient.java

public static <T> T executeUnderKerberos(String userName, String password, PrivilegedAction<T> action)
        throws IOException {

    final String errMsg = " You can still save the repository and start creating "
            + "policies, but you would not be able to use autocomplete for "
            + "resource names. Check xa_portal.log for more info.";
    class MySecureClientLoginConfiguration extends javax.security.auth.login.Configuration {

        private String userName;
        private String password;

        MySecureClientLoginConfiguration(String aUserName, String password) {
            this.userName = aUserName;
            this.password = password;
        }/*from  w ww  . jav  a2  s. c om*/

        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String appName) {

            Map<String, String> kerberosOptions = new HashMap<String, String>();
            kerberosOptions.put("principal", this.userName);
            kerberosOptions.put("debug", "true");
            kerberosOptions.put("useKeyTab", "false");
            kerberosOptions.put(KrbPasswordSaverLoginModule.USERNAME_PARAM, this.userName);
            kerberosOptions.put(KrbPasswordSaverLoginModule.PASSWORD_PARAM, this.password);
            kerberosOptions.put("doNotPrompt", "false");
            kerberosOptions.put("useFirstPass", "true");
            kerberosOptions.put("tryFirstPass", "false");
            kerberosOptions.put("storeKey", "true");
            kerberosOptions.put("refreshKrb5Config", "true");

            AppConfigurationEntry KEYTAB_KERBEROS_LOGIN = null;
            AppConfigurationEntry KERBEROS_PWD_SAVER = null;
            try {
                KEYTAB_KERBEROS_LOGIN = new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(),
                        AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, kerberosOptions);
                KERBEROS_PWD_SAVER = new AppConfigurationEntry(KrbPasswordSaverLoginModule.class.getName(),
                        LoginModuleControlFlag.REQUIRED, kerberosOptions);

            } catch (IllegalArgumentException e) {
                String msgDesc = "executeUnderKerberos: Exception while getting Storm TopologyList.";
                HadoopException hdpException = new HadoopException(msgDesc, e);
                LOG.error(msgDesc, e);

                hdpException.generateResponseDataMap(false, BaseClient.getMessage(e), msgDesc + errMsg, null,
                        null);
                throw hdpException;
            }

            LOG.debug("getAppConfigurationEntry():" + kerberosOptions.get("principal"));

            return new AppConfigurationEntry[] { KERBEROS_PWD_SAVER, KEYTAB_KERBEROS_LOGIN };
        }

    }
    ;

    T ret = null;

    Subject subject = null;
    LoginContext loginContext = null;

    try {
        subject = new Subject();
        LOG.debug("executeUnderKerberos():user=" + userName + ",pass=");
        LOG.debug("executeUnderKerberos():Creating config..");
        MySecureClientLoginConfiguration loginConf = new MySecureClientLoginConfiguration(userName, password);
        LOG.debug("executeUnderKerberos():Creating Context..");
        loginContext = new LoginContext("hadoop-keytab-kerberos", subject, null, loginConf);

        LOG.debug("executeUnderKerberos():Logging in..");
        loginContext.login();

        Subject loginSubj = loginContext.getSubject();

        if (loginSubj != null) {
            ret = Subject.doAs(loginSubj, action);
        }
    } catch (LoginException le) {
        String msgDesc = "executeUnderKerberos: Login failure using given"
                + " configuration parameters, username : `" + userName + "`.";
        HadoopException hdpException = new HadoopException(msgDesc, le);
        LOG.error(msgDesc, le);

        hdpException.generateResponseDataMap(false, BaseClient.getMessage(le), msgDesc + errMsg, null, null);
        throw hdpException;
    } catch (SecurityException se) {
        String msgDesc = "executeUnderKerberos: Exception while getting Storm TopologyList.";
        HadoopException hdpException = new HadoopException(msgDesc, se);
        LOG.error(msgDesc, se);

        hdpException.generateResponseDataMap(false, BaseClient.getMessage(se), msgDesc + errMsg, null, null);
        throw hdpException;

    } finally {
        if (loginContext != null) {
            if (subject != null) {
                try {
                    loginContext.logout();
                } catch (LoginException e) {
                    throw new IOException("logout failure", e);
                }
            }
        }
    }

    return ret;
}

From source file:fi.csc.mobileauth.shibboleth.rest.MobileServiceLoginHandler.java

public static Subject getResponse(String loginContextKey) {
    if (communicationDataStore.containsKey(loginContextKey)) {
        Map<String, String> attributes = communicationDataStore.getData(loginContextKey).getAttributes();
        if (attributes == null) {
            log.warn("No response attributes found for {} to be returned", loginContextKey);
            return null;
        }//from  w ww  . j a v  a2  s .  c  om
        log.debug("List of attributes size {}", attributes.size());
        final Subject userSubject = new Subject();
        String mobileNumber = attributes.get(StatusResponse.ATTRIBUTE_ID_MSISDN);
        if (mobileNumber == null) {
            log.warn("Could not obtain mobile number from the response attributes for {}", loginContextKey);
            return null;
        }
        String hookAttribute = DatatypeHelper
                .safeTrimOrNullString(attributes.get(userIdentifierResolver.getHookAttributeName()));
        if (hookAttribute == null) {
            log.debug("Populating the attributes to the Principal objects");
            return populatePrincipals(userSubject, attributes, mobileNumber);
        }
        String username = userIdentifierResolver.getUserIdentifier(hookAttribute);
        log.debug("Resolved username {} to mobile number {}", username, mobileNumber);
        if (username != null) {
            userSubject.getPrincipals().add(new UsernamePrincipal(username));
        } else {
            userSubject.getPrincipals().add(new MobileNumberPrincipal(mobileNumber));
        }
        return userSubject;
    }
    log.warn("No data stored for {}, could not return response object", loginContextKey);
    return null;
}

From source file:org.openhab.io.net.http.SecureHttpContext.java

/**
 * <p>Authenticates the given <code>username</code> and <code>password</code>
 * with respect to the given <code>realm</code> against the configured
 * {@link LoginModule} (see login.conf in &lt;openhabhome&gt;/etc to learn
 * more about the configured {@link LoginModule})</p>
 * <p><b>Note:</b>Roles aren't supported yet!</p>
 * /*  www.j  a v a 2s .  c o  m*/
 * @param realm the realm used by the configured {@link LoginModule}. 
 * <i>Note:</i> the given <code>realm</code> must be same name as configured
 * in <code>login.conf</code>
 * @param username
 * @param password
 * 
 * @return a {@link Subject} filled with username, password, realm, etc. or
 * <code>null</code> if the login failed
 * @throws UnsupportedCallbackException if a {@link Callback}-instance other
 * than {@link NameCallback} or {@link ObjectCallback} is going to be handled
 */
private Subject authenticate(final String realm, final String username, final String password) {
    try {
        logger.trace("going to authenticate user '{}', realm '{}'", username, realm);

        Subject subject = new Subject();

        LoginContext lContext = new LoginContext(realm, subject, new CallbackHandler() {
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                for (int i = 0; i < callbacks.length; i++) {
                    if (callbacks[i] instanceof NameCallback) {
                        ((NameCallback) callbacks[i]).setName(username);
                    } else if (callbacks[i] instanceof ObjectCallback) {
                        ((ObjectCallback) callbacks[i]).setObject(password);
                    } else {
                        throw new UnsupportedCallbackException(callbacks[i]);
                    }
                }
            }
        });
        lContext.login();

        // TODO: TEE: implement role handling here!

        return subject;
    } catch (LoginException le) {
        logger.warn("authentication of user '" + username + "' failed", le);
        return null;
    }
}