Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package logincontext;
- import java.io.IOException;
- import javax.security.auth.login.LoginContext;
- import javax.security.auth.login.LoginException;
- import javax.security.auth.Subject;
- import java.security.PrivilegedExceptionAction;
- import java.security.PrivilegedActionException;
- import java.io.*;
- public class Main {
- public static void main(String[] args) {
- try{
- LoginContext lc = new LoginContext("sergey", new MyCallbackHandler());
- lc.login();
- final Subject subj = lc.getSubject();
- try {
- Subject.doAsPrivileged(subj, new PrivilegedExceptionAction() {
- public Object run() {
- String message = "Initializing principal..";
- try {
- if(subj.getPrincipals().iterator().next().getName().equals("sergey")){
- File f = new File("hello.txt");
- message = "Hello from first principal: sergey!";
- f.createNewFile();
- FileOutputStream outStream = new FileOutputStream(f);
- outStream.write("Hello Bobby!".getBytes());
- outStream.flush();
- System.out.println("created file: " + f.getCanonicalPath());
- return message;
- }else if(subj.getPrincipals().iterator().next().getName().equals("bobby")){
- message = "Hello from second principal: bobby!";
- BufferedReader fis = new BufferedReader(new InputStreamReader(new FileInputStream("hello.txt")));
- System.out.println("Message:"+fis.readLine());
- return message;
- }else{
- System.out.println("Invalid principal.");
- return message;
- }
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- return message;
- } catch (IOException e) {
- e.printStackTrace();
- return message;
- }
- }
- }, null);
- } catch (PrivilegedActionException e) {
- e.printStackTrace();
- }
- }catch(LoginException e){
- e.printStackTrace();
- }
- }
- }
- ---------------------------
- package logincontext;
- import java.io.IOException;
- import javax.security.auth.callback.Callback;
- import javax.security.auth.callback.UnsupportedCallbackException;
- import javax.security.auth.callback.CallbackHandler;
- import javax.security.auth.callback.TextOutputCallback;
- import javax.security.auth.callback.PasswordCallback;
- import javax.security.auth.callback.NameCallback;
- import java.io.*;
- import java.util.Arrays;
- class MyCallbackHandler implements CallbackHandler {
- public void handle(Callback[] callbacks)
- throws IOException, UnsupportedCallbackException {
- for (int i = 0; i < callbacks.length; i++) {
- if (callbacks[i] instanceof TextOutputCallback) {
- // display the message according to the specified type
- TextOutputCallback toc = (TextOutputCallback)callbacks[i];
- switch (toc.getMessageType()) {
- case TextOutputCallback.INFORMATION:
- System.out.println(toc.getMessage());
- break;
- case TextOutputCallback.ERROR:
- System.out.println("ERROR: " + toc.getMessage());
- break;
- case TextOutputCallback.WARNING:
- System.out.println("WARNING: " + toc.getMessage());
- break;
- default:
- throw new IOException("Unsupported message type: " +
- toc.getMessageType());
- }
- } else if (callbacks[i] instanceof NameCallback) {
- // prompt the user for a username
- NameCallback nc = (NameCallback)callbacks[i];
- System.err.print(nc.getPrompt());
- System.err.flush();
- nc.setName((new BufferedReader
- (new InputStreamReader(System.in))).readLine());
- } else if (callbacks[i] instanceof PasswordCallback) {
- // prompt the user for sensitive information
- PasswordCallback pc = (PasswordCallback)callbacks[i];
- System.err.print(pc.getPrompt());
- System.err.flush();
- pc.setPassword(readPassword(System.in));
- } else {
- throw new UnsupportedCallbackException
- (callbacks[i], "Unrecognized Callback");
- }
- }
- }
- // Reads user password from given input stream.
- private char[] readPassword(InputStream in) throws IOException {
- char[] lineBuffer;
- char[] buf;
- int i;
- buf = lineBuffer = new char[128];
- int room = buf.length;
- int offset = 0;
- int c;
- loop: while (true) {
- switch (c = in.read()) {
- case -1:
- case '\n':
- break loop;
- case '\r':
- int c2 = in.read();
- if ((c2 != '\n') && (c2 != -1)) {
- if (!(in instanceof PushbackInputStream)) {
- in = new PushbackInputStream(in);
- }
- ((PushbackInputStream)in).unread(c2);
- } else
- break loop;
- default:
- if (--room < 0) {
- buf = new char[offset + 128];
- room = buf.length - offset - 1;
- System.arraycopy(lineBuffer, 0, buf, 0, offset);
- Arrays.fill(lineBuffer, ' ');
- lineBuffer = buf;
- }
- buf[offset++] = (char) c;
- break;
- }
- }
- if (offset == 0) {
- return null;
- }
- char[] ret = new char[offset];
- System.arraycopy(buf, 0, ret, 0, offset);
- Arrays.fill(buf, ' ');
- return ret;
- }
- }
- ---------------------------------
- package logincontext;
- import java.util.*;
- import javax.security.auth.*;
- import javax.security.auth.callback.*;
- import javax.security.auth.login.*;
- import javax.security.auth.spi.*;
- import java.security.Principal;
- import myprincipal.MyPrincipal;
- public class MyLoginModule implements LoginModule{
- // initial state
- private Subject subject;
- private CallbackHandler callbackHandler;
- private Map sharedState;
- private Map options;
- // configurable option
- private boolean debug = false;
- // the authentication status
- private boolean succeeded = false;
- private boolean commitSucceeded = false;
- // username and password
- private String username;
- private char[] password;
- // testUser's SamplePrincipal
- private Principal userPrincipal;
- public void initialize(Subject subject, CallbackHandler callbackHandler,
- Map sharedState, Map options) {
- this.subject = subject;
- this.callbackHandler = callbackHandler;
- this.sharedState = sharedState;
- this.options = options;
- // initialize any configured options
- debug = "true".equalsIgnoreCase((String)options.get("debug"));
- }
- public boolean login() throws LoginException {
- // prompt for a user name and password
- if (callbackHandler == null)
- throw new LoginException("Error: no CallbackHandler available " +
- "to garner authentication information from the user");
- Callback[] callbacks = new Callback[2];
- callbacks[0] = new NameCallback("user name: ");
- callbacks[1] = new PasswordCallback("password: ", false);
- try {
- callbackHandler.handle(callbacks);
- username = ((NameCallback)callbacks[0]).getName();
- char[] tmpPassword = ((PasswordCallback)callbacks[1]).getPassword();
- if (tmpPassword == null) {
- // treat a NULL password as an empty password
- tmpPassword = new char[0];
- }
- password = new char[tmpPassword.length];
- System.arraycopy(tmpPassword, 0,
- password, 0, tmpPassword.length);
- ((PasswordCallback)callbacks[1]).clearPassword();
- } catch (java.io.IOException ioe) {
- throw new LoginException(ioe.toString());
- } catch (UnsupportedCallbackException uce) {
- throw new LoginException("Error: " + uce.getCallback().toString() +
- " not available to garner authentication information " +
- "from the user");
- }
- // print debugging information
- if (debug) {
- System.out.println("\t\t[SampleLoginModule] " +
- "user entered user name: " +
- username);
- System.out.print("\t\t[SampleLoginModule] " +
- "user entered password: ");
- for (int i = 0; i < password.length; i++)
- System.out.print(password[i]);
- System.out.println();
- }
- // verify the username/password
- boolean usernameCorrect = false;
- boolean passwordCorrect = false;
- if ((username.equals("sergey"))||(username.equals("bobby")))
- usernameCorrect = true;
- if (usernameCorrect &&
- password.length == 8 &&
- password[0] == '1' &&
- password[1] == 'q' &&
- password[2] == '2' &&
- password[3] == 'w' &&
- password[4] == '3' &&
- password[5] == 'e' &&
- password[6] == '4' &&
- password[7] == 'r') {
- // authentication succeeded!!!
- passwordCorrect = true;
- if (debug)
- System.out.println("\t\t[SampleLoginModule] " +
- "authentication succeeded");
- succeeded = true;
- return true;
- } else {
- // authentication failed -- clean out state
- if (debug)
- System.out.println("\t\t[SampleLoginModule] " +
- "authentication failed");
- succeeded = false;
- username = null;
- for (int i = 0; i < password.length; i++)
- password[i] = ' ';
- password = null;
- if (!usernameCorrect) {
- throw new FailedLoginException("User Name Incorrect");
- } else {
- throw new FailedLoginException("Password Incorrect");
- }
- }
- }
- public boolean commit() throws LoginException {
- if (succeeded == false) {
- return false;
- } else {
- // add a Principal (authenticated identity)
- // to the Subject
- // assume the user we authenticated is the SamplePrincipal
- userPrincipal = new MyPrincipal(username);
- if (!subject.getPrincipals().contains(userPrincipal))
- subject.getPrincipals().add(userPrincipal);
- if (debug) {
- System.out.println("\t\t[SampleLoginModule] " +
- "added SamplePrincipal to Subject");
- }
- // in any case, clean out state
- username = null;
- for (int i = 0; i < password.length; i++)
- password[i] = ' ';
- password = null;
- commitSucceeded = true;
- return true;
- }
- }
- public boolean abort() throws LoginException {
- if (succeeded == false) {
- return false;
- } else if (succeeded == true && commitSucceeded == false) {
- // login succeeded but overall authentication failed
- succeeded = false;
- username = null;
- if (password != null) {
- for (int i = 0; i < password.length; i++)
- password[i] = ' ';
- password = null;
- }
- userPrincipal = null;
- } else {
- // overall authentication succeeded and commit succeeded,
- // but someone else's commit failed
- logout();
- }
- return true;
- }
- public boolean logout() throws LoginException {
- subject.getPrincipals().remove(userPrincipal);
- succeeded = false;
- succeeded = commitSucceeded;
- username = null;
- if (password != null) {
- for (int i = 0; i < password.length; i++)
- password[i] = ' ';
- password = null;
- }
- userPrincipal = null;
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement