10
Login Panel import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.awt.event.*; import java.util.*; /** * Title: Login Panel * Description: A simple yet complete login/logout panel with user callbacks * for approving login attempts and getting notification of logouts. * Copyright: Copyright (c) 2004 * Company: Superliminal Software * @author Melinda Green * @version 1.0 */ public class LoginPanel extends JPanel { public final static String LOG_IN = "Login", LOG_OUT = "Logout"; protected JButton logButt; public JButton getLogButton() { return logButt; } private final static int DEFAULT_PSWD_CHARS = 10; private JTextField nameField = new JTextField(DEFAULT_PSWD_CHARS); public String getUserName() { return nameField.getText(); } /** * override this method to return true if approved, false otherwise. * default is true. */ public boolean approveLogin(String uname, String pswd) { return true; } /** * override this method to learn about logout events. */ public void loggedOut(String uname) { } public LoginPanel() {

Login Panel

Embed Size (px)

Citation preview

Page 1: Login Panel

Login Panelimport javax.swing.*;import javax.swing.border.EmptyBorder;import java.awt.*;import java.awt.event.*;import java.util.*;

/** * Title: Login Panel * Description: A simple yet complete login/logout panel with user callbacks * for approving login attempts and getting notification of logouts. * Copyright: Copyright (c) 2004 * Company: Superliminal Software * @author Melinda Green * @version 1.0 */

public class LoginPanel extends JPanel { public final static String LOG_IN = "Login", LOG_OUT = "Logout"; protected JButton logButt; public JButton getLogButton() { return logButt; } private final static int DEFAULT_PSWD_CHARS = 10; private JTextField nameField = new JTextField(DEFAULT_PSWD_CHARS); public String getUserName() { return nameField.getText(); }

/** * override this method to return true if approved, false otherwise. * default is true. */ public boolean approveLogin(String uname, String pswd) { return true; }

/** * override this method to learn about logout events. */ public void loggedOut(String uname) { }

public LoginPanel() { this(false); }

public LoginPanel(final boolean clearPasswords) { this(clearPasswords, true, null, null); }

/**

Page 2: Login Panel

* @param clearPasswords if true, clears password field on successful login. * @param initial_user optional default text to load into the 'user' type-in. * @param initial_password optional default text to load into the 'password' type-in. */ public LoginPanel(final boolean clearPasswords, final boolean displayFailures, String initial_user, String initial_password) { final JPasswordField pswdField = new JPasswordField(DEFAULT_PSWD_CHARS); logButt = new JButton(LOG_IN); KeyListener quickLogin = new KeyAdapter() { public void keyTyped(KeyEvent ke) { if(ke.getKeyChar() == KeyEvent.VK_ENTER) { logButt.doClick(); logButt.requestFocus(); } } }; nameField.setText(initial_user); pswdField.setText(initial_password); logButt.setName(LOG_IN); nameField.addKeyListener(quickLogin); pswdField.addKeyListener(quickLogin); // create the grid JPanel grid = new JPanel(new GridLayout(2, 2)); grid.setBackground(new Color(255,255,255)); grid.add(new JLabel("User Name")); grid.add(nameField); grid.add(new JLabel("Password")); grid.add(pswdField);

// create login button row JPanel row = new JPanel(); row.setBorder(new EmptyBorder(5, 0, 5, 0)); row.setOpaque(false); row.setLayout(new BoxLayout(row, BoxLayout.X_AXIS)); row.add(logButt); logButt.setBackground(new Color(220,220,220));

logButt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { if(logButt.getText().equals(LOG_IN)) { // seek login approval from derived class if(approveLogin(nameField.getText(), new String(pswdField.getPassword()))) { // note: must set logout text *before* clearing password // otherwise component dependancy handler will disable the // login button w/out password text before later setting logout text // this closes bug #2336 logButt.setText(LOG_OUT); if(clearPasswords) pswdField.setText(null);

Page 3: Login Panel

nameField.setEnabled(false); pswdField.setEnabled(false); fireLoginEvent(nameField.getText(), true); } else if(displayFailures) JOptionPane.showMessageDialog(LoginPanel.this, "Login Denied", "Login Error", JOptionPane.ERROR_MESSAGE); } else { logButt.setText(LOG_IN); loggedOut(nameField.getText()); nameField.setEnabled(true); pswdField.setEnabled(true); fireLoginEvent(nameField.getText(), false); } } });

// implement component dependancies new ComponentDependencyHandler(nameField, pswdField) { public void dependencyNotification() { String logtext = logButt.getText(), nametext = nameField.getText(), pswdtext = String.copyValueOf(pswdField.getPassword()); boolean newstate = logtext.equalsIgnoreCase(LOG_OUT) || (nameField.getText() != null && nametext.length() > 0 // has login text? && pswdtext.length() > 0); // has password text? logButt.setEnabled(newstate); } };

// construct final layout setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); add(grid); add(row); }

public interface LoginListener { void loggedIn(String uname); void loggedOut(String uname); } public static class LoginAdapter implements LoginListener { public void loggedIn(String uname){} public void loggedOut(String uname){} } private Vector loginListeners = new Vector(); public void addLoginListener(LoginListener ll) { loginListeners.add(ll); } public void removeLoginListener(LoginListener ll) { loginListeners.remove(ll); } protected void fireLoginEvent(String uname, boolean in) { for(Enumeration e=loginListeners.elements(); e.hasMoreElements(); ) { LoginListener ll = (LoginListener)e.nextElement(); if(in) ll.loggedIn(uname);

Page 4: Login Panel

else ll.loggedOut(uname); } }

/** * simple example test program for LoginPanel class */ public static void main(String[] args) { final String NOT_LOGGED_IN = "LoginPanel Test - Currently Logged Out"; final JFrame frame = new JFrame(NOT_LOGGED_IN); frame.getContentPane().add(new LoginPanel() { public boolean approveLogin(String uname, String pswd) { // this is where to make the server call to approve or reject login attempt frame.setTitle("LoginPanel Test - Currently logged in as " + uname); return true; } public void loggedOut(String uname) { frame.setTitle(NOT_LOGGED_IN); } }); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setSize(500, frame.getHeight()); frame.setVisible(true); }}

Pass. Changes

import javax.swing.*;import java.awt.*;import java.awt.event.*;

/** * PasswordChanger is a simple dialog that allows users to enter their old password * and to reequest a new one. An abstract callback method is used to validate or reject * user entries. * Copyright: Copyright (c) 2004 * Company: Superliminal Software * * @author Melinda Green * Date: Aug 2, 2004

Page 5: Login Panel

*/public abstract class PasswordChanger extends JDialog { /** * Creates and displays a PasswordChanger object. * NOTE: Callers should not call setVisible() on these objects * and should throw away any instances once their acceptPasswordChange callback returns 'true'. * @param owner same as JDialog constuctor * @param uname user name used in title */ public PasswordChanger(JFrame owner, String uname) { super(owner, "Changing Password For " + uname, true); JPanel typeins = new JPanel(new GridLayout(3, 2)); final JPasswordField old = new JPasswordField(14), try1 = new JPasswordField(14), try2 = new JPasswordField(14); typeins.add(new JLabel("Old Password: ")); typeins.add(old); typeins.add(new JLabel("New Password: ")); typeins.add(try1); typeins.add(new JLabel("Retype Password: ")); typeins.add(try2); final JButton changeit = new JButton("Change Password"); changeit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(acceptPasswordChange(new String(old.getPassword()), new String(try1.getPassword()))) { JOptionPane.showMessageDialog(PasswordChanger.this, "Password Changed"); setVisible(false); } else JOptionPane.showMessageDialog(PasswordChanger.this, "Invalid Password"); } }); // allow for <enter> key in text fields to click button when enabled KeyListener quickchange = new KeyAdapter() { public void keyTyped(KeyEvent ke) { if(ke.getKeyChar() == KeyEvent.VK_ENTER && changeit.isEnabled()) { changeit.doClick(); changeit.requestFocus(); } } }; old.addKeyListener(quickchange); try1.addKeyListener(quickchange); try2.addKeyListener(quickchange); // enforce that the 'changeit' button is only enabled when valid data is ready. new ComponentDependencyHandler(old, try1, try2) { public void dependencyNotification() { String op = new String(old.getPassword()), t1 = new String(try1.getPassword()),

Page 6: Login Panel

t2 = new String(try2.getPassword()); changeit.setEnabled(t1.equalsIgnoreCase(t2) && !t1.equalsIgnoreCase(op)); } }; // create the final layout and show the dialog Container content = getContentPane(); content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS)); content.add(typeins); content.add(changeit); pack(); if(owner != null) setLocation(owner.getX()+50, owner.getY()+50); setVisible(true); } // end PasswordChanger()

/** * Implement this method to approve or reject a new password. * @param oldpswd what the user declares to be their current password. * @param newpswd user's equested new password. * @return true if old password entered matches current system value, and new password is acceptible. */ protected abstract boolean acceptPasswordChange(String oldpswd, String newpswd);

/** * a simple example main method that presents a PasswordChanger that accepts a new password of "pass" */ public static void main(String[] args) { new PasswordChanger(null, "Joe") { protected boolean acceptPasswordChange(String oldpswd, String newpswd) { return "pass".equalsIgnoreCase(newpswd); } }; }}

Login import java.security.Principal;import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;

Page 7: Login Panel

 @Controllerpublic class LoginController { 

@RequestMapping(value="/welcome", method = RequestMethod.GET)public String printWelcome(ModelMap model, Principal principal ) {

 String name = principal.getName();model.addAttribute("username", name);model.addAttribute("message", "Spring Security Custom Form example");return "hello";

 }

 @RequestMapping(value="/login", method = RequestMethod.GET)public String login(ModelMap model) {

 return "login";

 }

 @RequestMapping(value="/loginfailed", method = RequestMethod.GET)public String loginerror(ModelMap model) {

 model.addAttribute("error", "true");return "login";

 }

 @RequestMapping(value="/logout", method = RequestMethod.GET)public String logout(ModelMap model) {

 return "login";

 }

 }

Login<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><html><head><title>Login Page</title><style>.errorblock {

color: #ff0000;background-color: #ffEEEE;border: 3px solid #ff0000;padding: 8px;margin: 16px;

}</style></head><body onload='document.f.j_username.focus();'>

<h3>Login with Username and Password (Custom Page)</h3>

Page 8: Login Panel

 <c:if test="${not empty error}">

<div class="errorblock">Your login attempt was not successful, try again.<br />

Caused :${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}

</div></c:if>

 <form name='f' action="<c:url value='j_spring_security_check' />"

method='POST'> 

<table><tr>

<td>User:</td><td><input type='text' name='j_username' value=''></td>

</tr><tr>

<td>Password:</td><td><input type='password' name='j_password' /></td>

</tr><tr>

<td colspan='2'><input name="submit" type="submit"value="submit" />

</td></tr><tr>

<td colspan='2'><input name="reset" type="reset" /></td>

</tr></table>

 </form>

</body></html>

File : hello.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><html><body>

<h3>Message : ${message}</h3><h3>Username : ${username}</h3>

 <a href="<c:url value="/j_spring_security_logout" />" > Logout</a>

 </body></html>