Wednesday, February 17, 2016

Hadoop Simple Authentication using java

Following is the sample java program to take the advantage of Hadoop UserGroupInfomation to perform a simple authentication by impersonating a user.

import org.apache.hadoop.conf.*;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileStatus;

public class SimpleSecurity {

    public static void main(String args[]) {

        try {
            UserGroupInformation ugi
                    = UserGroupInformation.createRemoteUser("rsingh");

            ugi.doAs(new PrivilegedExceptionAction<Void>() {

                public Void run() throws Exception {

                    Configuration conf = new Configuration();
                    conf.set("fs.defaultFS", "maprfs:///");
                    conf.set("hadoop.job.ugi", "rsingh");


                    FileSystem fs = FileSystem.get(conf);


                    fs.createNewFile(new Path("/user/rsingh/test"));


                    FileStatus[] status = fs.listStatus(new Path("/user/rsingh"));

                    for(int i=0;i<status.length;i++){

                        System.out.println(status[i].getPath());

                    }

                    return null;

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Compile and Run this code
javac -cp `hadoop classpath` SimpleSecurity.java 
ava -cp .:`hadoop classpath` SimpleSecurity
16/02/17 03:08:17 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
16/02/17 03:08:18 INFO fs.MapRFileSystem: User root is impersonating user rsingh
maprfs:///user/rsingh/test

No comments: