Integrating Spring Security pt 2

In a previous post, I gave guidance on how to start using Spring Security to lock down a web application backed by a MySQL database. I’d like to provide another useful resource, this utility class for accessing the username of the currently logged-in user. This class is helpful for finding the current user logged in, or his or her IP address. More details may be retrievable by the Principal object if you implement it with more and cast it. See my subsequent post to see more.

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.Principal;

import org.apache.log4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

/**
 * Utility to aide in retrieving user information from Spring Security.
 *
 * @author Ben ([email protected])
 * @since Dec 31, 2012
 */
public class SpringSecurityContextUtil {

    private static Logger log = Logger.getLogger(SpringSecurityContextUtil.class);

    /**
     * Get the current principal, which is the embodiment of the user logged in.
     *
     * @return Principal, or null if none is found.
     */
    public static Principal getPrincipal() {
        Principal principal = null;
        SecurityContext context = SecurityContextHolder.getContext();
        if (context != null) {
            principal = context.getAuthentication();
        }
        return principal;
    }

    /**
     * Get the name of the principal.
     *
     * @return String, or null if no principal or name exists.
     */
    public static String getPrincipalName() {
        Principal p = getPrincipal();
        if (p != null)
            return p.getName();
        else
            return null;
    }

    /**
     * Get the IP address of the user.
     *
     * @return String of the IP address, or null if not found.
     */
    public static String getPrincipalIPAddess() {
        String address = null;
        SecurityContext context = SecurityContextHolder.getContext();
        if (context != null) {
            Authentication auth = context.getAuthentication();
            if (auth != null) {
                Object details = auth.getDetails();
                if (details instanceof WebAuthenticationDetails) {
                    address = ((WebAuthenticationDetails) details).getRemoteAddress();
                }
            }
        }

        if (address == null) {
            try {
                InetAddress addr = InetAddress.getLocalHost();
                address = addr.getHostAddress();
            } catch (UnknownHostException e) {
                log.warn(e);
            }
        }

        return address;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *