Advertisement
Guest User

Untitled

a guest
Jun 1st, 2017
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.01 KB | None | 0 0
  1. package logincontext;
  2. import java.io.IOException;
  3. import javax.security.auth.login.LoginContext;
  4. import javax.security.auth.login.LoginException;
  5. import javax.security.auth.Subject;
  6. import java.security.PrivilegedExceptionAction;
  7. import java.security.PrivilegedActionException;
  8. import java.io.*;
  9.  
  10. public class Main {
  11.  
  12.    
  13.     public static void main(String[] args) {
  14.         try{
  15.         LoginContext lc = new LoginContext("sergey", new MyCallbackHandler());
  16.         lc.login();
  17.         final Subject subj = lc.getSubject();
  18.                 try {
  19.             Subject.doAsPrivileged(subj, new PrivilegedExceptionAction() {
  20.                 public Object run() {
  21.                      String message = "Initializing principal..";                  
  22.                      try {
  23.                     if(subj.getPrincipals().iterator().next().getName().equals("sergey")){
  24.                     File f = new File("hello.txt");
  25.  
  26.                    message = "Hello from first principal: sergey!";
  27.                         f.createNewFile();
  28.                         FileOutputStream outStream = new FileOutputStream(f);
  29.                         outStream.write("Hello Bobby!".getBytes());
  30.                         outStream.flush();
  31.                         System.out.println("created file: " + f.getCanonicalPath());
  32.                         return message;
  33.                    
  34.                 }else if(subj.getPrincipals().iterator().next().getName().equals("bobby")){
  35.                     message = "Hello from second principal: bobby!";
  36.                 BufferedReader fis = new BufferedReader(new InputStreamReader(new FileInputStream("hello.txt")));
  37.                 System.out.println("Message:"+fis.readLine());
  38.                 return message;
  39.                 }else{
  40.                 System.out.println("Invalid principal.");
  41.                 return message;
  42.                 }
  43.                      } catch (FileNotFoundException e) {
  44.                         e.printStackTrace();
  45.                         return message;
  46.                     } catch (IOException e) {
  47.                         e.printStackTrace();
  48.                         return message;
  49.                     }                
  50.                 }
  51.             }, null);
  52.         } catch (PrivilegedActionException e) {
  53.             e.printStackTrace();
  54.         }
  55.         }catch(LoginException e){
  56.             e.printStackTrace();
  57.         }
  58.     }
  59.  
  60. }
  61.  
  62. ---------------------------
  63.  
  64. package logincontext;
  65.  
  66. import java.io.IOException;
  67. import javax.security.auth.callback.Callback;
  68. import javax.security.auth.callback.UnsupportedCallbackException;
  69. import javax.security.auth.callback.CallbackHandler;
  70. import javax.security.auth.callback.TextOutputCallback;
  71. import javax.security.auth.callback.PasswordCallback;
  72. import javax.security.auth.callback.NameCallback;
  73. import java.io.*;
  74. import java.util.Arrays;
  75.  
  76. class MyCallbackHandler implements CallbackHandler {
  77.  
  78.     public void handle(Callback[] callbacks)
  79.     throws IOException, UnsupportedCallbackException {
  80.      
  81.     for (int i = 0; i < callbacks.length; i++) {
  82.         if (callbacks[i] instanceof TextOutputCallback) {
  83.      
  84.         // display the message according to the specified type
  85.         TextOutputCallback toc = (TextOutputCallback)callbacks[i];
  86.         switch (toc.getMessageType()) {
  87.         case TextOutputCallback.INFORMATION:
  88.             System.out.println(toc.getMessage());
  89.             break;
  90.         case TextOutputCallback.ERROR:
  91.             System.out.println("ERROR: " + toc.getMessage());
  92.             break;
  93.         case TextOutputCallback.WARNING:
  94.             System.out.println("WARNING: " + toc.getMessage());
  95.             break;
  96.         default:
  97.             throw new IOException("Unsupported message type: " +
  98.                     toc.getMessageType());
  99.         }
  100.  
  101.         } else if (callbacks[i] instanceof NameCallback) {
  102.  
  103.         // prompt the user for a username
  104.         NameCallback nc = (NameCallback)callbacks[i];
  105.  
  106.         System.err.print(nc.getPrompt());
  107.         System.err.flush();
  108.         nc.setName((new BufferedReader
  109.             (new InputStreamReader(System.in))).readLine());
  110.  
  111.         } else if (callbacks[i] instanceof PasswordCallback) {
  112.  
  113.         // prompt the user for sensitive information
  114.         PasswordCallback pc = (PasswordCallback)callbacks[i];
  115.         System.err.print(pc.getPrompt());
  116.         System.err.flush();
  117.         pc.setPassword(readPassword(System.in));
  118.  
  119.         } else {
  120.         throw new UnsupportedCallbackException
  121.             (callbacks[i], "Unrecognized Callback");
  122.         }
  123.     }
  124.     }
  125.    
  126.     // Reads user password from given input stream.
  127.     private char[] readPassword(InputStream in) throws IOException {
  128.    
  129.     char[] lineBuffer;
  130.     char[] buf;
  131.     int i;
  132.  
  133.     buf = lineBuffer = new char[128];
  134.  
  135.     int room = buf.length;
  136.     int offset = 0;
  137.     int c;
  138.  
  139. loop:   while (true) {
  140.         switch (c = in.read()) {
  141.         case -1:
  142.         case '\n':
  143.         break loop;
  144.  
  145.         case '\r':
  146.         int c2 = in.read();
  147.         if ((c2 != '\n') && (c2 != -1)) {
  148.             if (!(in instanceof PushbackInputStream)) {
  149.             in = new PushbackInputStream(in);
  150.             }
  151.             ((PushbackInputStream)in).unread(c2);
  152.         } else
  153.             break loop;
  154.  
  155.         default:
  156.         if (--room < 0) {
  157.             buf = new char[offset + 128];
  158.             room = buf.length - offset - 1;
  159.             System.arraycopy(lineBuffer, 0, buf, 0, offset);
  160.             Arrays.fill(lineBuffer, ' ');
  161.             lineBuffer = buf;
  162.         }
  163.         buf[offset++] = (char) c;
  164.         break;
  165.         }
  166.     }
  167.  
  168.     if (offset == 0) {
  169.         return null;
  170.     }
  171.  
  172.     char[] ret = new char[offset];
  173.     System.arraycopy(buf, 0, ret, 0, offset);
  174.     Arrays.fill(buf, ' ');
  175.  
  176.     return ret;
  177.     }
  178. }
  179.  
  180. ---------------------------------
  181.  
  182. package logincontext;
  183. import java.util.*;
  184. import javax.security.auth.*;
  185. import javax.security.auth.callback.*;
  186. import javax.security.auth.login.*;
  187. import javax.security.auth.spi.*;
  188. import java.security.Principal;
  189. import myprincipal.MyPrincipal;
  190.  
  191.  
  192. public class MyLoginModule implements LoginModule{
  193.     // initial state
  194.     private Subject subject;
  195.     private CallbackHandler callbackHandler;
  196.     private Map sharedState;
  197.     private Map options;
  198.         // configurable option
  199.     private boolean debug = false;
  200.  
  201.     // the authentication status
  202.     private boolean succeeded = false;
  203.     private boolean commitSucceeded = false;
  204.  
  205.     // username and password
  206.     private String username;
  207.     private char[] password;
  208.    
  209.     // testUser's SamplePrincipal
  210.     private Principal userPrincipal;
  211.  
  212.    
  213.     public void initialize(Subject subject, CallbackHandler callbackHandler,
  214.             Map sharedState, Map options) {
  215.  
  216.     this.subject = subject;
  217.     this.callbackHandler = callbackHandler;
  218.     this.sharedState = sharedState;
  219.     this.options = options;
  220.  
  221.     // initialize any configured options
  222.     debug = "true".equalsIgnoreCase((String)options.get("debug"));
  223.     }
  224.  
  225.         public boolean login() throws LoginException {
  226.  
  227.     // prompt for a user name and password
  228.     if (callbackHandler == null)
  229.         throw new LoginException("Error: no CallbackHandler available " +
  230.             "to garner authentication information from the user");
  231.  
  232.     Callback[] callbacks = new Callback[2];
  233.     callbacks[0] = new NameCallback("user name: ");
  234.     callbacks[1] = new PasswordCallback("password: ", false);
  235.  
  236.     try {
  237.         callbackHandler.handle(callbacks);
  238.         username = ((NameCallback)callbacks[0]).getName();
  239.         char[] tmpPassword = ((PasswordCallback)callbacks[1]).getPassword();
  240.         if (tmpPassword == null) {
  241.         // treat a NULL password as an empty password
  242.         tmpPassword = new char[0];
  243.         }
  244.         password = new char[tmpPassword.length];
  245.         System.arraycopy(tmpPassword, 0,
  246.             password, 0, tmpPassword.length);
  247.         ((PasswordCallback)callbacks[1]).clearPassword();
  248.  
  249.     } catch (java.io.IOException ioe) {
  250.         throw new LoginException(ioe.toString());
  251.     } catch (UnsupportedCallbackException uce) {
  252.         throw new LoginException("Error: " + uce.getCallback().toString() +
  253.         " not available to garner authentication information " +
  254.         "from the user");
  255.     }
  256.  
  257.     // print debugging information
  258.     if (debug) {
  259.         System.out.println("\t\t[SampleLoginModule] " +
  260.                 "user entered user name: " +
  261.                 username);
  262.         System.out.print("\t\t[SampleLoginModule] " +
  263.                 "user entered password: ");
  264.         for (int i = 0; i < password.length; i++)
  265.         System.out.print(password[i]);
  266.         System.out.println();
  267.     }
  268.  
  269.     // verify the username/password
  270.     boolean usernameCorrect = false;
  271.     boolean passwordCorrect = false;
  272.     if ((username.equals("sergey"))||(username.equals("bobby")))
  273.         usernameCorrect = true;
  274.     if (usernameCorrect &&
  275.         password.length == 8 &&
  276.         password[0] == '1' &&
  277.         password[1] == 'q' &&
  278.         password[2] == '2' &&
  279.         password[3] == 'w' &&
  280.         password[4] == '3' &&
  281.         password[5] == 'e' &&
  282.         password[6] == '4' &&
  283.         password[7] == 'r') {
  284.  
  285.         // authentication succeeded!!!
  286.         passwordCorrect = true;
  287.         if (debug)
  288.         System.out.println("\t\t[SampleLoginModule] " +
  289.                 "authentication succeeded");
  290.         succeeded = true;
  291.         return true;
  292.     } else {
  293.  
  294.         // authentication failed -- clean out state
  295.         if (debug)
  296.         System.out.println("\t\t[SampleLoginModule] " +
  297.                 "authentication failed");
  298.         succeeded = false;
  299.         username = null;
  300.         for (int i = 0; i < password.length; i++)
  301.         password[i] = ' ';
  302.         password = null;
  303.         if (!usernameCorrect) {
  304.         throw new FailedLoginException("User Name Incorrect");
  305.         } else {
  306.         throw new FailedLoginException("Password Incorrect");
  307.         }
  308.     }
  309.     }
  310.         public boolean commit() throws LoginException {
  311.     if (succeeded == false) {
  312.         return false;
  313.     } else {
  314.         // add a Principal (authenticated identity)
  315.         // to the Subject
  316.  
  317.         // assume the user we authenticated is the SamplePrincipal
  318.         userPrincipal = new MyPrincipal(username);
  319.         if (!subject.getPrincipals().contains(userPrincipal))
  320.         subject.getPrincipals().add(userPrincipal);
  321.  
  322.         if (debug) {
  323.         System.out.println("\t\t[SampleLoginModule] " +
  324.                 "added SamplePrincipal to Subject");
  325.         }
  326.  
  327.         // in any case, clean out state
  328.         username = null;
  329.         for (int i = 0; i < password.length; i++)
  330.         password[i] = ' ';
  331.         password = null;
  332.  
  333.         commitSucceeded = true;
  334.         return true;
  335.     }
  336.     }
  337.        
  338.            public boolean abort() throws LoginException {
  339.     if (succeeded == false) {
  340.         return false;
  341.     } else if (succeeded == true && commitSucceeded == false) {
  342.         // login succeeded but overall authentication failed
  343.         succeeded = false;
  344.         username = null;
  345.         if (password != null) {
  346.         for (int i = 0; i < password.length; i++)
  347.             password[i] = ' ';
  348.         password = null;
  349.         }
  350.         userPrincipal = null;
  351.     } else {
  352.         // overall authentication succeeded and commit succeeded,
  353.         // but someone else's commit failed
  354.         logout();
  355.     }
  356.     return true;
  357.     }
  358.  
  359.         public boolean logout() throws LoginException {
  360.  
  361.     subject.getPrincipals().remove(userPrincipal);
  362.     succeeded = false;
  363.     succeeded = commitSucceeded;
  364.     username = null;
  365.     if (password != null) {
  366.         for (int i = 0; i < password.length; i++)
  367.         password[i] = ' ';
  368.         password = null;
  369.     }
  370.     userPrincipal = null;
  371.     return true;
  372.     }
  373.  
  374. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement