AuthenticateNT.java Source code

Java tutorial

Introduction

Here is the source code for AuthenticateNT.java

Source

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.security.PrivilegedAction;

import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;

public class AuthenticateNT {
    public static void main(String[] args) {
        try {
            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);
        }
    }
}

class WriteFileAction implements PrivilegedAction {
    public Object run() {
        try {
            File file = new File("D:/", "privilegedFile.txt");
            FileWriter fileWriter = new FileWriter(file);

            fileWriter.write("Welcome to JAAS!");
            fileWriter.close();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }

        return null;

    }
}

/*
// java.policy
// Policy file that grants AllPermission to JAAS modules and specific permissions to the D:\Projects\Java codebase.
grant codebase "file:/D:/jdk1.3.1/jre/lib/ext/jaas.jar" {
   permission java.security.AllPermission;
}; 
    
grant codebase "file:/D:/JavaProjects/src/-" {
   permission javax.security.auth.AuthPermission 
  "createLoginContext";
    
   permission javax.security.auth.AuthPermission "doAs";
    
   permission java.io.FilePermission "D:/privilegedFile.txt", 
  "write";
    
   permission java.io.FilePermission "D:/privilegedFile.txt", 
  "read";
};
    
*/

/*
// jaas.policy
// Policy file defining the permissions for the named Principal
grant codeBase "file:D:/", 
   Principal com.sun.security.auth.NTUserPrincipal "santry" {
    
   permission java.io.FilePermission "D:/privilegedFile.txt", 
  "write";
    
   permission java.io.FilePermission "D:/privilegedFile.txt", 
  "read";
};
    
*/

/*
// jaas.config 
// Configures JAAS to use NTLoginModule
// for authentication.
AuthenticateNT {
   com.sun.security.auth.module.NTLoginModule required debug=false;
};
    
*/