FileDocCategorySizeDatePackage
SecurityUtils.javaAPI DocExample2908Thu Sep 02 16:18:30 BST 2004com.oreilly.strutsckbk.ch11

SecurityUtils

public class SecurityUtils extends Object
Utility methods for in Security. This class contains static methods that can manipulate cookies containing a user's credentials.

Fields Summary
private static final String
USERNAME_COOKIE
private static final String
PASSWORD_COOKIE
private static final int
COOKIE_MAX_AGE
Constructors Summary
private SecurityUtils()
Private default constructor to prevent inadvertent instantiation.

	
Methods Summary
public static final voidaddCredentials(Credentials credentials, javax.servlet.http.HttpServletResponse response)
Adds a cookie containing the user's credentials to the servlet response.

param
credentials user authentication credentials.
param
response HTTP servlet response.

 // 30 days

                               
	        
		Cookie unameCookie = new Cookie(USERNAME_COOKIE, credentials.getName());
        unameCookie.setMaxAge(COOKIE_MAX_AGE);
        response.addCookie(unameCookie);
        Cookie pwordCookie = new Cookie(PASSWORD_COOKIE, credentials.getPassword());
        pwordCookie.setMaxAge(COOKIE_MAX_AGE);
		response.addCookie(pwordCookie);
	
public static final CredentialsfindCredentials(javax.servlet.http.HttpServletRequest request)
Searches for the user's credentials stored as a cookie in the servlet request.

param
request HTTP servlet request.
return
credentials.

		Cookie[] cookies = request.getCookies();
        String username = null;
        String password = null;
		if (cookies != null) {
			for (int i=0; i<cookies.length; i++) {
				if (cookies[i].getName().equals(USERNAME_COOKIE)) {
					username = cookies[i].getValue();
				}
                if (cookies[i].getName().equals(PASSWORD_COOKIE)) {
                    password = cookies[i].getValue();
                }
			}
		}
        if (username != null && password != null) {
            return new Credentials(username, password);
        }
		return null;
	
public static final voidremoveCredentials(javax.servlet.http.HttpServletResponse response)
Removes a user's credentials by expiring the cookie.

param
request HTTP servlet response.

		Cookie unameCookie = new Cookie(USERNAME_COOKIE, "expired");
        // setting the max age to zero causes the cookie to be removed on the client-side
        unameCookie.setMaxAge(0);
        response.addCookie(unameCookie);

        Cookie pwordCookie = new Cookie(PASSWORD_COOKIE, "expired");
        // setting the max age to zero causes the cookie to be removed on the client-side
        pwordCookie.setMaxAge(0);
        response.addCookie(pwordCookie);