wsaxton
wsaxton

Reputation: 1082

How can I integrate SSO authentication with JSF?

I'm currently using a Filter to check for SSO authentication. (SSO is considered authenticated if the request header contains the variable "Proxy-Remote-User").

if (!(isSsoLoggedIn(request)) {
    response.sendRedirect(ERROR_PAGE);
    return;
} else {
    chain.doFilter(req, res);
}

private boolean isSsoLoggedIn(HttpServletRequest request) {
    return request != null && request.getHeader("Proxy-Remote-User") != null
            && !request.getHeader("Proxy-Remote-User").equals("");
}

Now, once the user is authenticated, I want to pass that variable (which is an email address) to JSF. I do that with a session-scoped bean:

@PostConstruct
public void init {
    Map<String, String> requestHeaderMap = FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap();
    String email = requestHeaderMap.get("Proxy-Remote-User");
    user = getPersonFromDB(email);
}

This seems simple enough, but I'm not sure if its the "right" way to do this. It doesn't seem correct to rely on a bean's instantiation to verify authentication.

One idea I just had: Use a CDI session-scoped bean and @Inject it into the Filter. Then, you could have the filter itself check for a valid user and, if valid, set it in the session-scoped bean, otherwise forward it to an error page.

Does that sound like a valid solution?

Another approach could be to have every page check for authentication, before the view is rendered, with a view param as mentioned here:

JSF calls methods when managed bean constructor sends 404 ERROR CODE

<f:metadata>
    <f:viewAction action="#{bean.checkForValidUser}" />
</f:metadata>

The only problem I have for this is...this would require copying/pasting the same code to every page which seems redundant (or at least a template for them all to use).

Upvotes: 1

Views: 4192

Answers (1)

wsaxton
wsaxton

Reputation: 1082

Here is the answer I came up with (thanks to some tips from @BalusC).

I check to see if developer login is enabled or SSO has been authenticated. Once I have the email address, I see if its a valid user, verify the JSF session contains the right user, and, if so, forward them on their way.

/**
 * This filter handles SSO login (or developer login) privileges to the web
 * application.
 */
@WebFilter(servletNames = "Faces Servlet")
public class SecurityFilter implements Filter {

    @Inject
    private SessionManager sessionManager;

    @EJB
    private PersonWriteFacadeRemote personFacade;

    private HttpServletRequest currentRequest;
    private HttpServletResponse currentResponse;

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        currentRequest = (HttpServletRequest) req;
        currentResponse = (HttpServletResponse) res;
        HttpSession session = currentRequest.getSession();
        String requestedPage = currentRequest.getRequestURI();

            // check if the session is initialized
        // if not, initialize it
        if (!isSessionInitialized()) {
            Person user = getCurrentUser();

            // if we can't figure out who the user is, then send 401 error
            if (user != null) {
                initializeSession(user);
            } else {
                currentResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            }

                // if it is initialized, check if it actually matches the current
            // user
            // if not, invalidate the session and redirect them back to the page
            // to reinitialize it
        } else if (!isSessionCurrentUsers()) {
            session.invalidate();
            currentResponse.sendRedirect(requestedPage);
            return;
        }

        chain.doFilter(req, res); // If all looks good, continue the request

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    private Person getCurrentUser() {
        try {
            return personFacade.createFromEmail(getUserEmail());
        } catch (InvalidAttributesException ex) {
            Logger.getLogger(SecurityFilter.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    private String getUserEmail() {
        return isDevLoginEnabled() ? getUserEmailFromJndi() : getUserEmailFromSso();
    }

    private String getUserEmailFromJndi() {
        return JNDI.lookup("devLoginEmail");
    }

    private String getUserEmailFromSso() {
        return currentRequest != null && currentRequest.getHeader("Proxy-Remote-User") != null
                && !currentRequest.getHeader("Proxy-Remote-User").equals("")
                        ? currentRequest.getHeader("Proxy-Remote-User") : null;
    }

    private boolean isDevLoginEnabled() {
        Boolean devLoginEnabled = JNDI.lookup("devLoginEnabled");
        return (devLoginEnabled != null ? devLoginEnabled : false);
    }

    private boolean isSessionInitialized() {
        return sessionManager.getUser() != null;
    }

    private void initializeSession(Person user) {
        sessionManager.initializeSession(user);
    }

    private boolean isSessionCurrentUsers() {
        return sessionManager.getUser() != null && sessionManager.getUser().getEmail() != null
                && sessionManager.getUser().getEmail().equals(getUserEmail());
    }
}

Upvotes: 1

Related Questions