Example usage for javax.security.auth Subject doAs

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

Introduction

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

Prototype

public static <T> T doAs(final Subject subject, final java.security.PrivilegedExceptionAction<T> action)
        throws java.security.PrivilegedActionException 

Source Link

Document

Perform work as a particular Subject .

Usage

From source file:AuthenticateNT.java

public static void main(String[] args) {
    try {/*from  w w w . j  a v  a2s  .c o  m*/
        LoginContext loginContext = new LoginContext("AuthenticateNT");
        loginContext.login();
        System.out.println("Login Successful");
        Subject subject = loginContext.getSubject();
        System.out.println(subject);
        Subject.doAs(subject, new WriteFileAction());
        loginContext.logout();
        System.exit(0);
    } catch (LoginException loginException) {
        loginException.printStackTrace();
        System.exit(-1);
    }
}

From source file:uk.ac.ox.webauth.WebauthGetTokensRequest.java

/**
 * Simple test method that tries to post the request to the WebKDC and parse
 * the response message./*  w  ww . j ava  2 s.  c o  m*/
 * @param   args    First principal and then the keytab to load a key from,
 *          then the service to generate the KRB_AP_REQ message for,
 *          then the url to post the request to.
 * @throws  Exception   when something goes wrong.
 */
public static void main(String[] args) throws Exception {
    // get some keys to decrypt with
    long start = System.currentTimeMillis();
    KeytabKeyLoader kkl = new KeytabKeyLoader(args[0], args[1], false);
    Subject sub = kkl.acquire();
    long stop = System.currentTimeMillis();
    System.out.println("Grabbing private key took " + (stop - start) + " milliseconds.");

    // grab the service ticket
    start = System.currentTimeMillis();
    try {
        Subject.doAs(sub, new ServiceTicketGrabberHack(args[0], args[2]));
    } catch (Exception e) {
        e.printStackTrace();
    }
    KerberosTicket ticket = null;
    for (KerberosTicket t : sub.getPrivateCredentials(KerberosTicket.class)) {
        if (t.getServer().getName().startsWith(args[2])) {
            ticket = t;
        }
    }
    stop = System.currentTimeMillis();
    System.out.println("Getting the service ticket took " + (stop - start) + " milliseconds.");

    // request a webkdc token
    start = System.currentTimeMillis();
    byte[] krb_ap_req = new KrbApReq(ticket).toASN1Object().getEncoded();
    WebauthGetTokensRequest wgtr = new WebauthGetTokensRequest(args[3], krb_ap_req);
    wgtr.tokenRequest();
    stop = System.currentTimeMillis();
    System.out.println("Getting the WebKDC token took " + (stop - start) + " milliseconds.");
    System.out.println("Token data: " + wgtr.tokenData());
    System.out.println("Session key: " + wgtr.sessionKey());
    System.out.println("Expires: " + wgtr.expires());
    System.out.println("Success.");
}

From source file:com.logiclander.jaasmine.SPNegoClient.java

public SPNegoClient(Subject subject, AuthenticationType type) throws GSSException, PrivilegedActionException {
    // create a GSS Credential using a JAAS Subject that has Kerberos
    // ticket(s)/*from w w  w  . j  a v a  2s  . co  m*/
    gssClientCred = Subject.doAs(subject, new CredentialGenerator(gssManager, type.getOidValue()));

}

From source file:org.apache.jxtadoop.security.authorize.ServiceAuthorizationManager.java

/**
 * Check if the given {@link Subject} has all of necessary {@link Permission} 
 * set./*from   ww  w.  j  a v a2  s.c  o  m*/
 * 
 * @param user <code>Subject</code> to be authorized
 * @param permissions <code>Permission</code> set
 * @throws AuthorizationException if the authorization failed
 */
private static void checkPermission(final Subject user, final Permission... permissions)
        throws AuthorizationException {
    try {
        Subject.doAs(user, new PrivilegedExceptionAction<Void>() {
            public Void run() throws Exception {
                try {
                    for (Permission permission : permissions) {
                        AccessController.checkPermission(permission);
                    }
                } catch (AccessControlException ace) {
                    LOG.info("Authorization failed for " + UserGroupInformation.getCurrentUGI(), ace);
                    throw new AuthorizationException(ace);
                }
                return null;
            }
        });
    } catch (PrivilegedActionException e) {
        throw new AuthorizationException(e.getException());
    }
}

From source file:org.apache.hive.service.auth.HttpAuthUtils.java

/**
 * @return Stringified Base64 encoded kerberosAuthHeader on success
 * @throws Exception//www .  jav  a 2 s  .com
 */
public static String getKerberosServiceTicket(String principal, String host, String serverHttpUrl,
        boolean assumeSubject) throws Exception {
    String serverPrincipal = ShimLoader.getHadoopThriftAuthBridge().getServerPrincipal(principal, host);
    if (assumeSubject) {
        // With this option, we're assuming that the external application,
        // using the JDBC driver has done a JAAS kerberos login already
        AccessControlContext context = AccessController.getContext();
        Subject subject = Subject.getSubject(context);
        if (subject == null) {
            throw new Exception("The Subject is not set");
        }
        return Subject.doAs(subject, new HttpKerberosClientAction(serverPrincipal, serverHttpUrl));
    } else {
        // JAAS login from ticket cache to setup the client UserGroupInformation
        UserGroupInformation clientUGI = ShimLoader.getHadoopThriftAuthBridge()
                .getCurrentUGIWithConf("kerberos");
        return clientUGI.doAs(new HttpKerberosClientAction(serverPrincipal, serverHttpUrl));
    }
}

From source file:org.apache.ranger.hive.client.HiveClient.java

public void initHive() {
    isKerberosAuth = getConfigHolder().isKerberosAuthentication();
    if (isKerberosAuth) {
        LOG.info("Secured Mode: JDBC Connection done with preAuthenticated Subject");
        Subject.doAs(getLoginSubject(), new PrivilegedAction<Object>() {
            public Object run() {
                initConnection();/*from w  w  w .  jav a 2s  .  co m*/
                return null;
            }
        });
    } else {
        LOG.info("Since Password is NOT provided, Trying to use UnSecure client with username and password");
        final String userName = getConfigHolder().getUserName();
        final String password = getConfigHolder().getPassword();
        Subject.doAs(getLoginSubject(), new PrivilegedAction<Object>() {
            public Object run() {
                initConnection(userName, password);
                return null;
            }
        });
    }
}

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 {//www  .  j  a v a2s.c o  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.springframework.security.extensions.kerberos.SunJaasKerberosTicketValidator.java

public String validateTicket(byte[] token) {
    String username = null;//from  w w w.j  a  v a2s. c o  m
    try {
        username = Subject.doAs(this.serviceSubject, new KerberosValidateAction(token));
    } catch (PrivilegedActionException e) {
        throw new BadCredentialsException("Kerberos validation not succesfull", e);
    }
    return username;
}

From source file:org.pentaho.di.core.auth.kerberos.LoginContextInvocationHandler.java

@Override
public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable {
    try {//from  w  w  w.  j a v a  2s. c om
        return Subject.doAs(loginContext.getSubject(), new PrivilegedExceptionAction<Object>() {

            @Override
            public Object run() throws Exception {
                Object result = method.invoke(delegate, args);
                if (result != null) {
                    for (Class<?> iface : result.getClass().getInterfaces()) {
                        if (interfacesToDelegate.contains(iface)) {
                            result = forObject(result, loginContext, interfacesToDelegate);
                            break;
                        }
                    }
                }
                return result;
            }
        });
    } catch (PrivilegedActionException e) {
        if (e.getCause() instanceof InvocationTargetException) {
            throw ((InvocationTargetException) e.getCause()).getCause();
        }
        throw e;
    }
}

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

@Override
public KerberosTicketValidation validateTicket(byte[] token) {
    try {//from w w  w .j  a v a 2s. c  om
        return Subject.doAs(this.serviceSubject, new KerberosValidateAction(token));
    } catch (PrivilegedActionException e) {
        throw new BadCredentialsException("Kerberos validation not successful", e);
    }
}