Example usage for javax.servlet.http HttpServletRequest getUserPrincipal

List of usage examples for javax.servlet.http HttpServletRequest getUserPrincipal

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getUserPrincipal.

Prototype

public java.security.Principal getUserPrincipal();

Source Link

Document

Returns a java.security.Principal object containing the name of the current authenticated user.

Usage

From source file:com.egt.core.jsf.JSF.java

public static Principal getPrincipal() {
    HttpServletRequest request = getRequest();
    return request == null ? null : request.getUserPrincipal();
}

From source file:org.apache.servicemix.http.processors.ConsumerProcessor.java

private Context createContext(HttpServletRequest request) throws Exception {
    String content = streamToString(request.getInputStream());
    SoapMessage message = soapHelper.getSoapMarshaler().createReader()
            .read(new ByteArrayInputStream(content.getBytes()), request.getHeader(HEADER_CONTENT_TYPE));
    logInMessage(request.getContextPath(), content);
    Context ctx = soapHelper.createContext(message);
    if (request.getUserPrincipal() != null) {
        if (request.getUserPrincipal() instanceof JaasJettyPrincipal) {
            Subject subject = ((JaasJettyPrincipal) request.getUserPrincipal()).getSubject();
            ctx.getInMessage().setSubject(subject);
        } else {/*from   ww w . ja v a  2  s . co m*/
            ctx.getInMessage().addPrincipal(request.getUserPrincipal());
        }
    }
    return ctx;
}

From source file:io.hops.hopsworks.api.user.AuthService.java

private void logUserLogin(HttpServletRequest req) {
    StringBuilder roles = new StringBuilder();
    roles.append(req.isUserInRole("HOPS_USER") ? "{user" : "{");
    roles.append(req.isUserInRole("HOPS_ADMIN") ? " admin" : "");
    roles.append(req.isUserInRole("AGENT") ? " agent" : "");
    roles.append(req.isUserInRole("CLUSTER_AGENT") ? " cluster-agent}" : "}");
    LOGGER.log(Level.INFO, "[/hopsworks-api] login:\n email: {0}\n session: {1}\n in roles: {2}",
            new Object[] { req.getUserPrincipal(), req.getSession().getId(), roles });
}

From source file:org.picketlink.social.standalone.login.ExternalAuthentication.java

protected boolean processOpenID(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Principal userPrincipal = request.getUserPrincipal();
    if (userPrincipal != null) {
        if (trace)
            log.trace("Logged in as:" + userPrincipal);
        return true;
    }/*w  w  w  . ja  v a 2  s .  c o  m*/

    if (!openidProcessor.isInitialized()) {
        try {
            openidProcessor.initialize(roles);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    HttpSession httpSession = request.getSession();
    String state = (String) httpSession.getAttribute("STATE");
    if (trace)
        log.trace("state=" + state);

    if (STATES.FINISH.name().equals(state)) {
        // This is a replay. We need to resend a request back to the OpenID provider
        httpSession.setAttribute("STATE", STATES.AUTH.name());

        return prepareAndSendAuthRequest(request, response);
    }

    if (state == null || state.isEmpty()) {
        return prepareAndSendAuthRequest(request, response);
    }
    // We have sent an auth request
    if (state.equals(STATES.AUTH.name())) {
        Principal principal = processIncomingAuthResult(request, response);

        if (principal == null) {
            log.error(
                    "Principal was null. Maybe login modules need to be configured properly. Or user chose no data");
            return false;
        }

        return dealWithOpenIDPrincipal(request, response, principal);
    }
    return false;
}

From source file:edu.nwpu.gemfire.monitor.controllers.PulseController.java

@RequestMapping(value = "/getQueryStatisticsGridModel", method = RequestMethod.GET)
public void getQueryStatisticsGridModel(HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    ObjectNode responseJSON = mapper.createObjectNode();
    // get cluster object
    Cluster cluster = Repository.get().getCluster();
    String userName = request.getUserPrincipal().getName();

    try {// w  w w  .  j  a va 2 s .  c  om
        String[] arrColNames = Cluster.Statement.getGridColumnNames();
        String[] arrColAttribs = Cluster.Statement.getGridColumnAttributes();
        int[] arrColWidths = Cluster.Statement.getGridColumnWidths();

        ArrayNode colNamesList = mapper.createArrayNode();
        for (int i = 0; i < arrColNames.length; ++i) {
            colNamesList.add(arrColNames[i]);
        }

        ArrayNode colModelList = mapper.createArrayNode();
        for (int i = 0; i < arrColAttribs.length; ++i) {
            ObjectNode columnJSON = mapper.createObjectNode();
            columnJSON.put("name", arrColAttribs[i]);
            columnJSON.put("index", arrColAttribs[i]);
            columnJSON.put("width", arrColWidths[i]);
            columnJSON.put("sortable", "true");
            columnJSON.put("sorttype", ((i == 0) ? "String" : "integer"));
            colModelList.add(columnJSON);
        }

        responseJSON.put("columnNames", colNamesList);
        responseJSON.put("columnModels", colModelList);
        responseJSON.put("clusterName", cluster.getServerName());
        responseJSON.put("userName", userName);

        // Send json response
        response.getOutputStream().write(responseJSON.toString().getBytes());
    } catch (Exception e) {
        if (LOGGER.fineEnabled()) {
            LOGGER.fine("Exception Occured : " + e.getMessage());
        }
    }
}

From source file:org.apache.catalina.authenticator.FormAuthenticator.java

/**
 * Authenticate the user making this request, based on the specified
 * login configuration.  Return <code>true</code> if any specified
 * constraint has been satisfied, or <code>false</code> if we have
 * created a response challenge already.
 *
 * @param request Request we are processing
 * @param response Response we are creating
 * @param config    Login configuration describing how authentication
 *              should be performed/*from  ww w . ja  v a  2 s . c o  m*/
 *
 * @exception IOException if an input/output error occurs
 */
public boolean authenticate(HttpRequest request, HttpResponse response, LoginConfig config) throws IOException {

    // References to objects we will need later
    HttpServletRequest hreq = (HttpServletRequest) request.getRequest();
    HttpServletResponse hres = (HttpServletResponse) response.getResponse();
    Session session = null;

    // Have we already authenticated someone?
    Principal principal = hreq.getUserPrincipal();
    String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE);
    if (principal != null) {
        if (log.isDebugEnabled())
            log.debug("Already authenticated '" + principal.getName() + "'");
        // Associate the session with any existing SSO session
        if (ssoId != null)
            associate(ssoId, getSession(request, true));
        return (true);
    }

    // Is there an SSO session against which we can try to reauthenticate?
    if (ssoId != null) {
        if (log.isDebugEnabled())
            log.debug("SSO Id " + ssoId + " set; attempting " + "reauthentication");
        // Try to reauthenticate using data cached by SSO.  If this fails,
        // either the original SSO logon was of DIGEST or SSL (which
        // we can't reauthenticate ourselves because there is no
        // cached username and password), or the realm denied
        // the user's reauthentication for some reason.
        // In either case we have to prompt the user for a logon */
        if (reauthenticateFromSSO(ssoId, request))
            return true;
    }

    // Have we authenticated this user before but have caching disabled?
    if (!cache) {
        session = getSession(request, true);
        if (log.isDebugEnabled())
            log.debug("Checking for reauthenticate in session " + session);
        String username = (String) session.getNote(Constants.SESS_USERNAME_NOTE);
        String password = (String) session.getNote(Constants.SESS_PASSWORD_NOTE);
        if ((username != null) && (password != null)) {
            if (log.isDebugEnabled())
                log.debug("Reauthenticating username '" + username + "'");
            principal = context.getRealm().authenticate(username, password);
            if (principal != null) {
                session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);
                register(request, response, principal, Constants.FORM_METHOD, username, password);
                return (true);
            }
            if (log.isDebugEnabled())
                log.debug("Reauthentication failed, proceed normally");
        }
    }

    // Is this the re-submit of the original request URI after successful
    // authentication?  If so, forward the *original* request instead.
    if (matchRequest(request)) {
        session = getSession(request, true);
        if (log.isDebugEnabled())
            log.debug("Restore request from session '" + session.getId() + "'");
        principal = (Principal) session.getNote(Constants.FORM_PRINCIPAL_NOTE);
        register(request, response, principal, Constants.FORM_METHOD,
                (String) session.getNote(Constants.SESS_USERNAME_NOTE),
                (String) session.getNote(Constants.SESS_PASSWORD_NOTE));
        if (restoreRequest(request, session)) {
            if (log.isDebugEnabled())
                log.debug("Proceed to restored request");
            return (true);
        } else {
            if (log.isDebugEnabled())
                log.debug("Restore of original request failed");
            hres.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return (false);
        }
    }

    // Acquire references to objects we will need to evaluate
    MessageBytes uriMB = MessageBytes.newInstance();
    CharChunk uriCC = uriMB.getCharChunk();
    uriCC.setLimit(-1);
    String contextPath = hreq.getContextPath();
    String requestURI = request.getDecodedRequestURI();
    response.setContext(request.getContext());

    // Is this the action request from the login page?
    boolean loginAction = requestURI.startsWith(contextPath) && requestURI.endsWith(Constants.FORM_ACTION);

    // No -- Save this request and redirect to the form login page
    if (!loginAction) {
        session = getSession(request, true);
        if (log.isDebugEnabled())
            log.debug("Save request in session '" + session.getId() + "'");
        saveRequest(request, session);
        RequestDispatcher disp = context.getServletContext().getRequestDispatcher(config.getLoginPage());
        try {
            disp.forward(hreq, hres);
            response.finishResponse();
        } catch (Throwable t) {
            log.warn("Unexpected error forwarding to login page", t);
        }
        return (false);
    }

    // Yes -- Validate the specified credentials and redirect
    // to the error page if they are not correct
    Realm realm = context.getRealm();
    String username = hreq.getParameter(Constants.FORM_USERNAME);
    String password = hreq.getParameter(Constants.FORM_PASSWORD);
    if (log.isDebugEnabled())
        log.debug("Authenticating username '" + username + "'");
    principal = realm.authenticate(username, password);
    if (principal == null) {
        RequestDispatcher disp = context.getServletContext().getRequestDispatcher(config.getErrorPage());
        try {
            disp.forward(hreq, hres);
        } catch (Throwable t) {
            log.warn("Unexpected error forwarding to error page", t);
        }
        return (false);
    }

    // Save the authenticated Principal in our session
    if (log.isDebugEnabled())
        log.debug("Authentication of '" + username + "' was successful");
    if (session == null)
        session = getSession(request, true);
    session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);

    // If we are not caching, save the username and password as well
    if (!cache) {
        session.setNote(Constants.SESS_USERNAME_NOTE, username);
        session.setNote(Constants.SESS_PASSWORD_NOTE, password);
    }

    // Redirect the user to the original request URI (which will cause
    // the original request to be restored)
    requestURI = savedRequestURL(session);
    if (log.isDebugEnabled())
        log.debug("Redirecting to original '" + requestURI + "'");
    if (requestURI == null)
        hres.sendError(HttpServletResponse.SC_BAD_REQUEST, sm.getString("authenticator.formlogin"));
    else
        hres.sendRedirect(hres.encodeRedirectURL(requestURI));
    return (false);

}

From source file:com.pivotal.gemfire.tools.pulse.internal.controllers.PulseController.java

@RequestMapping(value = "/getQueryStatisticsGridModel", method = RequestMethod.GET)
public void getQueryStatisticsGridModel(HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    JSONObject responseJSON = new JSONObject();
    // get cluster object
    Cluster cluster = Repository.get().getCluster();
    String userName = request.getUserPrincipal().getName();

    try {/*ww  w.  ja  va2  s  . com*/
        String[] arrColNames = Cluster.Statement.getGridColumnNames();
        String[] arrColAttribs = Cluster.Statement.getGridColumnAttributes();
        int[] arrColWidths = Cluster.Statement.getGridColumnWidths();

        JSONArray colNamesList = new JSONArray();
        for (int i = 0; i < arrColNames.length; ++i) {
            colNamesList.put(arrColNames[i]);
        }

        JSONArray colModelList = new JSONArray();
        JSONObject columnJSON = null;
        for (int i = 0; i < arrColAttribs.length; ++i) {
            columnJSON = new JSONObject();
            columnJSON.put("name", arrColAttribs[i]);
            columnJSON.put("index", arrColAttribs[i]);
            columnJSON.put("width", arrColWidths[i]);
            columnJSON.put("sortable", "true");
            columnJSON.put("sorttype", ((i == 0) ? "String" : "integer"));
            colModelList.put(columnJSON);
        }

        responseJSON.put("columnNames", colNamesList);
        responseJSON.put("columnModels", colModelList);
        responseJSON.put("clusterName", cluster.getServerName());
        responseJSON.put("userName", userName);

        // Send json response
        response.getOutputStream().write(responseJSON.toString().getBytes());
    } catch (JSONException eJSON) {
        LOGGER.logJSONError(eJSON, null);
    } catch (Exception e) {
        if (LOGGER.fineEnabled()) {
            LOGGER.fine("Exception Occured : " + e.getMessage());
        }
    }
}

From source file:org.sakaiproject.nakamura.auth.trusted.TrustedTokenServiceTest.java

@Test
public void testInjectCookieUser() {
    ComponentContext context = configureForCookie();
    HttpServletRequest request = createMock(HttpServletRequest.class);
    Principal principal = createMock(Principal.class);
    EasyMock.expect(request.getRemoteAddr()).andReturn("192.168.0.127"); // not a trusted proxy

    EasyMock.expect(request.getUserPrincipal()).andReturn(principal);
    EasyMock.expect(principal.getName()).andReturn(null);
    EasyMock.expect(request.getRemoteUser()).andReturn("ieb");
    HttpServletResponse response = createMock(HttpServletResponse.class);
    Capture<Cookie> cookieCapture = new Capture<Cookie>();
    response.addCookie(EasyMock.capture(cookieCapture));
    EasyMock.expectLastCall();//from ww w. j  a  v  a  2  s .  c  om
    response.addHeader("Cache-Control", "no-cache=\"set-cookie\" ");
    expectLastCall();
    response.addDateHeader("Expires", 0);
    expectLastCall();

    replay();
    trustedTokenService.activate(context);
    trustedTokenService.injectToken(request, response, TrustedTokenTypes.AUTHENTICATED_TRUST, null);
    Assert.assertTrue(cookieCapture.hasCaptured());
    Cookie cookie = cookieCapture.getValue();
    Assert.assertNotNull(cookie);
    Assert.assertEquals("secure-cookie", cookie.getName());
    String[] user = trustedTokenService.decodeCookie(cookie.getValue());
    Assert.assertArrayEquals(new String[] { "ieb", TrustedTokenTypes.AUTHENTICATED_TRUST }, user);
    verify();
}

From source file:nl.b3p.kaartenbalie.struts.UserAction.java

protected boolean updatePrincipal(HttpServletRequest request, User user) {
    User sessUser = (User) request.getUserPrincipal();
    if (!sessUser.equals(user)) {
        return false;
    }/* w  w  w .j  a  v  a 2s  . c  o  m*/
    // need to update logged in user
    if (request instanceof SecurityRequestWrapper) {
        SecurityRequestWrapper srw = (SecurityRequestWrapper) request;
        srw.setUserPrincipal(user);
        return true;
    }
    return false;
}

From source file:com.duroty.application.files.actions.DownloadFileAction.java

/**
 * DOCUMENT ME!//from  w w  w.  j a v  a2  s .com
 *
 * @param request DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 */
protected Hashtable getContextProperties(HttpServletRequest request) {
    Hashtable props = (Hashtable) SessionManager.getObject(Constants.CONTEXT_PROPERTIES, request);

    if (props == null) {
        props = new Hashtable();

        props.put(Context.INITIAL_CONTEXT_FACTORY,
                Configuration.properties.getProperty(Configuration.JNDI_INITIAL_CONTEXT_FACTORY));
        props.put(Context.URL_PKG_PREFIXES,
                Configuration.properties.getProperty(Configuration.JNDI_URL_PKG_PREFIXES));
        props.put(Context.PROVIDER_URL, Configuration.properties.getProperty(Configuration.JNDI_PROVIDER_URL));

        Principal principal = request.getUserPrincipal();
        props.put(Context.SECURITY_PRINCIPAL, principal.getName());
        props.put(Context.SECURITY_CREDENTIALS, SessionManager.getObject(Constants.JAAS_PASSWORD, request));

        props.put(Context.SECURITY_PROTOCOL,
                Configuration.properties.getProperty(Configuration.SECURITY_PROTOCOL));

        SessionManager.setObject(Constants.CONTEXT_PROPERTIES, props, request);
    }

    return props;
}