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(boolean readOnly, Set<? extends Principal> principals, Set<?> pubCredentials,
        Set<?> privCredentials) 

Source Link

Document

Create an instance of a Subject with Principals and credentials.

Usage

From source file:org.mule.management.support.SimplePasswordJmxAuthenticator.java

public Subject authenticate(Object authToken) {
    if (authToken == null) {
        throw new SecurityException("No authentication token available");
    }//from ww  w.j av  a2s.  c o m
    if (!(authToken instanceof String[]) || ((String[]) authToken).length != 2) {
        throw new SecurityException("Unsupported credentials format");
    }

    String[] authentication = (String[]) authToken;

    String username = StringUtils.defaultString(authentication[0]);
    String password = StringUtils.defaultString(authentication[1]);

    if (!credentials.containsKey(username)) {
        throw new SecurityException("Unauthenticated user: " + username);
    }

    if (!password.equals(ObjectUtils.toString(credentials.get(username)))) {
        throw new SecurityException("Invalid password");
    }

    Set principals = new HashSet();
    principals.add(new JMXPrincipal(username));
    return new Subject(true, principals, Collections.EMPTY_SET, Collections.EMPTY_SET);
}

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

/**
 * Get the {@link Subject} for the user identified by <code>ugi</code>.
 * @param ugi user/*from   w w  w  .ja v  a  2 s .c  o m*/
 * @return the {@link Subject} for the user identified by <code>ugi</code>
 */
public static Subject getSubject(UserGroupInformation ugi) {
    if (ugi == null) {
        return null;
    }

    Set<Principal> principals = // Number of principals = username + #groups 
            new HashSet<Principal>(ugi.getGroupNames().length + 1);
    User userPrincipal = new User(ugi.getUserName());
    principals.add(userPrincipal);
    for (String group : ugi.getGroupNames()) {
        Group groupPrincipal = new Group(group);
        principals.add(groupPrincipal);
    }
    principals.add(ugi);
    Subject user = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());

    return user;
}

From source file:org.apache.nifi.hadoop.KerberosKeytabSPNegoScheme.java

@Override
public byte[] generateToken(byte[] input, String authServer, Credentials credentials) {
    Set<Principal> principals = new HashSet<>();
    principals.add(credentials.getUserPrincipal());
    Subject subject = new Subject(false, principals, new HashSet<>(), new HashSet<>());

    try {/*from  w w w . ja va 2  s . co  m*/
        LoginContext loginContext = new LoginContext("", subject, null,
                new KerberosConfiguration(credentials.getUserPrincipal().getName(),
                        ((KerberosKeytabCredentials) credentials).getKeytab()));
        loginContext.login();
        Subject loggedInSubject = loginContext.getSubject();

        return Subject.doAs(loggedInSubject, new PrivilegedExceptionAction<byte[]>() {

            public byte[] run() throws UnknownHostException, ClassNotFoundException, GSSException,
                    IllegalAccessException, NoSuchFieldException {
                GSSManager gssManager = GSSManager.getInstance();
                String servicePrincipal = KerberosUtil.getServicePrincipal("HTTP", authServer);
                Oid serviceOid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
                GSSName serviceName = gssManager.createName(servicePrincipal, serviceOid);
                Oid mechOid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
                GSSContext gssContext = gssManager.createContext(serviceName, mechOid, null, 0);
                gssContext.requestCredDeleg(true);
                gssContext.requestMutualAuth(true);
                return gssContext.initSecContext(input, 0, input.length);
            }

        });
    } catch (PrivilegedActionException | LoginException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.mule.module.management.support.SimplePasswordJmxAuthenticator.java

public Subject authenticate(Object authToken) {
    if (authToken == null) {
        throw new SecurityException("No authentication token available");
    }/* w  w  w  . java  2s . c  o  m*/
    if (!(authToken instanceof String[]) || ((String[]) authToken).length != 2) {
        throw new SecurityException("Unsupported credentials format");
    }

    String[] authentication = (String[]) authToken;

    String username = StringUtils.defaultString(authentication[0]);
    String password = StringUtils.defaultString(authentication[1]);

    if (!credentials.containsKey(username)) {
        throw new SecurityException("Unauthenticated user: " + username);
    }

    Object pass = credentials.get(username);
    if (!password.equals(pass == null ? "" : pass.toString())) {
        throw new SecurityException("Invalid password");
    }

    Set<Principal> principals = new HashSet<Principal>();
    principals.add(new JMXPrincipal(username));
    return new Subject(true, principals, Collections.EMPTY_SET, Collections.EMPTY_SET);
}

From source file:org.ow2.proactive.resourcemanager.rmnode.RMNodeHelper.java

public static Pair<RMNodeImpl, Node> basicWithMockedInternals(String nodeSourceName, Node node) {

    NodeSource nodeSource = Mockito.mock(NodeSource.class);

    Set<Principal> principals = new HashSet<>();
    principals.add(new UserNamePrincipal("provider"));

    Client provider = new Client(new Subject(false, principals, emptySet(), emptySet()), false);

    Permission permission = Mockito.mock(Permission.class);

    when(nodeSource.getName()).thenReturn(nodeSourceName);

    return new ImmutablePair<>(new RMNodeImpl(node, nodeSource, provider, permission), node);
}

From source file:com.flexive.core.security.LoginLogoutHandler.java

/**
 * Login function./*w  w  w. j  a v  a2 s.  c  o  m*/
 *
 * @param username The username
 * @param password The users password
 * @param takeOver If a other session is already logged in with this unique username the other session is
 *                 invalidated (logged out), and this session is logged in.
 * @param ctx      the session context
 * @param ds       the datasource to be used
 * @return The new UserTicket if the login succeeded, or null if the login failed.
 * @throws FxLoginFailedException  if the login failed
 * @throws FxAccountInUseException if a other session is already logged in (with this unique username) AND take
 *                                 over is false
 */
public static UserTicket doLogin(String username, String password, boolean takeOver, SessionContext ctx,
        DataSource ds) throws FxLoginFailedException, FxAccountInUseException {
    boolean success = false;
    try {
        // Actually logged in?
        UserTicket ticket = FxContext.getUserTicket();
        final boolean calledAsSupervisor = ticket.isGlobalSupervisor();
        if (!ticket.isGuest()) {
            doLogout();
        }

        // Try a login
        /*PassiveCallbackHandler pch = new PassiveCallbackHandler(username, password, takeOver, ctx, ds);
        LoginContext lc = new LoginContext(LOGIN_CTX, pch);
        lc.login();
        final Subject sub = lc.getSubject();
        ticket = FxDefaultLogin.getUserTicket(sub);*/
        final FxCallback callback = new FxCallback();
        callback.setTakeOverSession(takeOver);
        callback.setSessionContext(ctx);
        callback.setDataSource(ds);
        callback.setCalledAsSupervisor(calledAsSupervisor);
        ticket = FxAuthenticationHandler.login(username, password, callback);
        // Log out any other sessions of the user
        if (!ticket.isMultiLogin() && !ticket.isWebDav()) {
            // TODO: real logout?
            UserTicketStore.removeUserId(ticket.getUserId(), ticket.getApplicationId());
        }
        // Set session informations in cluster cache
        final Subject sub = new Subject(false, new HashSet<Principal>(Arrays.asList(new FxPrincipal(ticket))),
                new HashSet(), new HashSet());
        UserTicketStore.storeSubject(sub);
        // flag success
        success = true;
        EJBLookup.getHistoryTrackerEngine().track("history.account.login", ticket.getLoginName());
        // Return the ticket
        return ticket;
    } catch (FxLoginFailedException exc) {
        EJBLookup.getHistoryTrackerEngine().track("history.account.login.error", username);
        throw exc;
    } catch (FxAccountInUseException exc) {
        throw exc;
    } catch (Exception exc) {
        FxLoginFailedException le = new FxLoginFailedException(
                "Login failed (internal error): " + exc.getMessage(),
                FxLoginFailedException.TYPE_UNKNOWN_ERROR);
        LOG.error(le);
        throw le;
    } finally {
        if (!success)
            try {
                doLogout();
            } catch (Exception exc) {
                // ignore, this is only a cleanup attempt that will most likely fail
            }
    }
}

From source file:org.apache.qpid.server.management.plugin.HttpManagementUtil.java

public static void checkRequestAuthenticatedAndAccessAuthorized(HttpServletRequest request, Broker broker,
        HttpManagementConfiguration managementConfig) {
    HttpSession session = request.getSession();
    Subject subject = getAuthorisedSubject(session);
    if (subject == null) {
        subject = tryToAuthenticate(request, managementConfig);
        if (subject == null) {
            throw new SecurityException("Only authenticated users can access the management interface");
        }//from   www.  j a v a2  s  . c o m

        Subject original = subject;
        subject = new Subject(false, original.getPrincipals(), original.getPublicCredentials(),
                original.getPrivateCredentials());
        subject.getPrincipals().add(new ServletConnectionPrincipal(request));
        subject.setReadOnly();

        assertManagementAccess(broker.getSecurityManager(), subject);

        saveAuthorisedSubject(session, subject);

    }
}

From source file:org.adeptnet.auth.kerberos.Krb5.java

public String isTicketValid(String spn, byte[] ticket) {
    checkCreds();//from w  w w  . j av a 2 s .  c  o  m
    LoginContext ctx = null;
    try {
        if (!config.getKeytab().exists()) {
            throw new LoginException(
                    String.format("KeyTab does not exist: %s", config.getKeytab().getAbsolutePath()));
        }
        final Principal principal = new KerberosPrincipal(spn, KerberosPrincipal.KRB_NT_SRV_INST);
        Set<Principal> principals = new HashSet<>();
        principals.add(principal);

        final Subject subject = new Subject(false, principals, new HashSet<>(), new HashSet<>());

        ctx = new LoginContext(config.getContextName(), subject, null, getJaasKrb5TicketCfg(spn));
        ctx.login();

        final Krb5TicketValidateAction validateAction = new Krb5TicketValidateAction(ticket, spn);
        final String username = Subject.doAs(subject, validateAction);
        return username;
    } catch (java.security.PrivilegedActionException | LoginException e) {
        LOG.fatal(spn, e);
    } finally {
        try {
            if (ctx != null) {
                ctx.logout();
            }
        } catch (LoginException e2) {
            LOG.fatal(spn, e2);
        }
    }

    return FAILED;
}

From source file:org.springframework.security.kerberos.authentication.sun.SunJaasKerberosTicketValidator.java

@Override
public void afterPropertiesSet() throws Exception {
    Assert.notNull(this.servicePrincipal, "servicePrincipal must be specified");
    Assert.notNull(this.keyTabLocation, "keyTab must be specified");
    if (keyTabLocation instanceof ClassPathResource) {
        LOG.warn(/*www .  j a  v a2  s.com*/
                "Your keytab is in the classpath. This file needs special protection and shouldn't be in the classpath. JAAS may also not be able to load this file from classpath.");
    }
    String keyTabLocationAsString = this.keyTabLocation.getURL().toExternalForm();
    // We need to remove the file prefix (if there is one), as it is not supported in Java 7 anymore.
    // As Java 6 accepts it with and without the prefix, we don't need to check for Java 7
    if (keyTabLocationAsString.startsWith("file:")) {
        keyTabLocationAsString = keyTabLocationAsString.substring(5);
    }
    LoginConfig loginConfig = new LoginConfig(keyTabLocationAsString, this.servicePrincipal, this.debug);
    Set<Principal> princ = new HashSet<Principal>(1);
    princ.add(new KerberosPrincipal(this.servicePrincipal));
    Subject sub = new Subject(false, princ, new HashSet<Object>(), new HashSet<Object>());
    LoginContext lc = new LoginContext("", sub, null, loginConfig);
    lc.login();
    this.serviceSubject = lc.getSubject();
}

From source file:org.apache.sentry.provider.db.service.thrift.TestSentryWebServerWithKerberos.java

@Test
public void testPingWithUnauthorizedUser() throws Exception {
    // create an unauthorized User with Kerberos
    String userPrinciple = "user/" + SERVER_HOST;
    String userKerberosName = userPrinciple + "@" + REALM;
    Subject userSubject = new Subject(false, Sets.newHashSet(new KerberosPrincipal(userKerberosName)),
            new HashSet<Object>(), new HashSet<Object>());
    File userKeytab = new File(kdcWorkDir, "user.keytab");
    kdc.createPrincipal(userKeytab, userPrinciple);
    LoginContext userLoginContext = new LoginContext("", userSubject, null,
            KerberosConfiguration.createClientConfig(userKerberosName, userKeytab));
    userLoginContext.login();//from  ww w. j  av  a  2s. co  m
    Subject.doAs(userLoginContext.getSubject(), new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            final URL url = new URL("http://" + SERVER_HOST + ":" + webServerPort + "/ping");
            try {
                new AuthenticatedURL(new KerberosAuthenticator()).openConnection(url,
                        new AuthenticatedURL.Token());
                fail("Here should fail.");
            } catch (AuthenticationException e) {
                String expectedError = "status code: 403";
                if (!e.getMessage().contains(expectedError)) {
                    LOG.error("UnexpectedError: " + e.getMessage(), e);
                    fail("UnexpectedError: " + e.getMessage());
                }
            }
            return null;
        }
    });
}