Handling the Callbacks from a Login Module - Java Security

Java examples for Security:Login

Description

Handling the Callbacks from a Login Module

Demo Code


import java.io.IOException;
import java.util.Locale;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.LanguageCallback;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.TextOutputCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;

public class Main {
  public static void m() {
    try {//from w  w  w .  ja  v a  2  s  .c  o  m
      LoginContext lc = new LoginContext("LoginAppName",
          new MyCallbackHandler());
    } catch (LoginException e) {
      // Login failed
    }
  }
}

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) {
        // This callback delivers messages from a login module
        TextOutputCallback toCb = (TextOutputCallback) callbacks[i];

        // Get message
        String msg = toCb.getMessage();

        // Get message type
        switch (toCb.getMessageType()) {
        case TextOutputCallback.INFORMATION:
          break;
        case TextOutputCallback.ERROR:
          break;
        case TextOutputCallback.WARNING:
          break;
        }
      } else if (callbacks[i] instanceof NameCallback) {
        NameCallback nCb = (NameCallback) callbacks[i];
        String prompt = nCb.getPrompt();
        // Get the name ...
        nCb.setName("username");
      } else if (callbacks[i] instanceof PasswordCallback) {
        PasswordCallback pCb = (PasswordCallback) callbacks[i];
        String prompt = pCb.getPrompt();
        // Get the password ...
        pCb.setPassword("password".toCharArray());
      } else if (callbacks[i] instanceof LanguageCallback) {
        LanguageCallback lCb = (LanguageCallback) callbacks[i];
        // Get the locale ...
        lCb.setLocale(Locale.CHINESE);
      } else {
        throw new UnsupportedCallbackException(callbacks[i],
            "Unrecognized Callback");
      }
    }
  }
}

Related Tutorials