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:net.sourceforge.vulcan.web.SignedRequestAuthorizationFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {
    if (validate(request, secretKey)) {
        if (StringUtils.isNotBlank(principalParameterName) && request.getUserPrincipal() == null) {
            final String requestBy = request.getParameter(principalParameterName);
            if (StringUtils.isNotBlank(requestBy)) {
                request = new RequestWrapperWithPrincipal(request, new SignedRequestPrincipal(requestBy));
            }/*from ww w  .  j a  v  a 2s.c  om*/
        }
        chain.doFilter(request, response);
    } else {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
}

From source file:com.acentic.cloudservices.session.web.PublicActions.java

public String doLoginCasUser() {
    LOGGER.log(Level.TRACE, "do login cas user");

    SystemUserBean systemUser = null;//  w w w.  ja v a  2 s.  c  o  m
    try {
        HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
                .get(ServletActionContext.HTTP_REQUEST);
        AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();
        if (principal == null) {
            throw new Exception("principal is null");
        } else {
            @SuppressWarnings("rawtypes")
            Map attributes = principal.getAttributes();
            String uid = (String) attributes.get("uid");
            Long lUid = Long.valueOf(uid);
            systemUser = (SystemUserBean) applicationContext.getBean(SpringUserBeansDef.SystemUserBean, lUid);
            if (!systemUser.isLoaded()) {
                LOGGER.log(Level.ERROR, "unable to login cas user with id " + lUid);
                return ERROR;
            }

            LOGGER.log(Level.DEBUG, "request with local=" + request.getLocale().toString());
        }
    } catch (Exception e) {
        LOGGER.log(Level.ERROR, "unable to login cas user", e);
        return ERROR;
    }

    return SUCCESS;
}

From source file:org.nuxeo.ecm.liveconnect.google.drive.GoogleDriveBlobUploader.java

private boolean hasServiceAccount() {
    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();//from   www.  j  a va 2  s.  co m
    String username = request.getUserPrincipal().getName();
    GoogleOAuth2ServiceProvider provider = getGoogleDriveBlobProvider().getOAuth2Provider();
    return provider != null && provider.getServiceUser(username) != null;
}

From source file:org.polymap.core.security.SpnegoFilter.java

private void simple(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    String header = httpRequest.getHeader("Authorization");

    Principal principal = httpRequest.getUserPrincipal();
    if (principal instanceof SpnegoPrincipal) {
        SpnegoPrincipal spnegoPrincipal = (SpnegoPrincipal) principal;
        GSSCredential credentials = spnegoPrincipal.getDelegatedCredential();
        // if(credentials != null) {
        // response.getWriter().println("Found group SIDs: " +
        // Arrays.toString(groupSIDs));
        // } else {
        // response.getWriter().println("No logon info available for principal.");
        // }/*  w w  w. jav a2 s .  com*/
    } else {
        sendUnauthorized(httpResponse, true);
    }
}

From source file:org.springframework.boot.actuate.trace.WebRequestTraceFilter.java

protected Map<String, Object> getTrace(HttpServletRequest request) {
    HttpSession session = request.getSession(false);
    Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception");
    Principal userPrincipal = request.getUserPrincipal();
    Map<String, Object> trace = new LinkedHashMap<String, Object>();
    Map<String, Object> headers = new LinkedHashMap<String, Object>();
    trace.put("method", request.getMethod());
    trace.put("path", request.getRequestURI());
    trace.put("headers", headers);
    if (isIncluded(Include.REQUEST_HEADERS)) {
        headers.put("request", getRequestHeaders(request));
    }/*  w w  w.ja  va  2s  .  co m*/
    add(trace, Include.PATH_INFO, "pathInfo", request.getPathInfo());
    add(trace, Include.PATH_TRANSLATED, "pathTranslated", request.getPathTranslated());
    add(trace, Include.CONTEXT_PATH, "contextPath", request.getContextPath());
    add(trace, Include.USER_PRINCIPAL, "userPrincipal",
            (userPrincipal == null ? null : userPrincipal.getName()));
    add(trace, Include.PARAMETERS, "parameters", request.getParameterMap());
    add(trace, Include.QUERY_STRING, "query", request.getQueryString());
    add(trace, Include.AUTH_TYPE, "authType", request.getAuthType());
    add(trace, Include.REMOTE_ADDRESS, "remoteAddress", request.getRemoteAddr());
    add(trace, Include.SESSION_ID, "sessionId", (session == null ? null : session.getId()));
    add(trace, Include.REMOTE_USER, "remoteUser", request.getRemoteUser());
    if (isIncluded(Include.ERRORS) && exception != null && this.errorAttributes != null) {
        trace.put("error",
                this.errorAttributes.getErrorAttributes(new ServletRequestAttributes(request), true));
    }
    return trace;
}

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

private Organization getOrganization(DynaValidatorForm dynaForm, HttpServletRequest request) throws Exception {

    log.debug("Getting entity manager ......");
    EntityManager em = getEntityManager();
    Organization organization = null;//from www  . j  av  a  2s.c  o  m
    Integer id = getID(dynaForm);

    if (id == null) {
        User principalUser = (User) request.getUserPrincipal();
        if (principalUser == null) {
            return null;
        }
        User user = (User) em.find(User.class, principalUser.getId());
        if (user == null) {
            return null;
        }
        organization = user.getMainOrganization();
    } else {
        organization = (Organization) em.find(Organization.class, id);
    }

    return organization;
}

From source file:org.nuxeo.ecm.tokenauth.service.TokenAuthenticationServiceImpl.java

@Override
public String acquireToken(HttpServletRequest request) throws TokenAuthenticationException {
    Principal principal = request.getUserPrincipal();
    if (principal == null) {
        return null;
    }//w  ww  .  j av  a2s  . c o m

    // Don't provide token for anonymous user unless 'allowAnonymous' parameter is explicitly set to true in
    // the authentication plugin configuration
    if (principal instanceof NuxeoPrincipal && ((NuxeoPrincipal) principal).isAnonymous()) {
        PluggableAuthenticationService authenticationService = (PluggableAuthenticationService) Framework
                .getRuntime().getComponent(PluggableAuthenticationService.NAME);
        AuthenticationPluginDescriptor tokenAuthPluginDesc = authenticationService.getDescriptor("TOKEN_AUTH");
        if (tokenAuthPluginDesc == null || !(Boolean
                .valueOf(tokenAuthPluginDesc.getParameters().get(TokenAuthenticator.ALLOW_ANONYMOUS_KEY)))) {
            return null;
        }
    }

    String userName = principal.getName();
    String applicationName = request.getParameter("applicationName");
    String deviceId = request.getParameter("deviceId");
    String deviceDescription = request.getParameter("deviceDescription");
    String permission = request.getParameter("permission");

    return acquireToken(userName, applicationName, deviceId, deviceDescription, permission);
}

From source file:org.nuxeo.oauth2.SalesforceOAuth2ServiceProvider.java

/**
 * Retrieves or creates a service user.//  w  ww .  j  a  v  a  2s .  c  o m
 * Should be overriden by subclasses wanting to rely on a different field as key.
 */
protected String getOrCreateServiceUser(HttpServletRequest request, String accessToken) throws IOException {
    String nuxeoLogin = request.getUserPrincipal().getName();
    String userId = getServiceUserId(nuxeoLogin);
    if (userId == null) {
        userId = getServiceUserStore().store(nuxeoLogin);
    }

    return userId;
}

From source file:org.wso2.carbon.identity.application.authenticator.iwa.ntlm.servlet.IWAServlet.java

/**
 * Check whether the request is already authenticated using IWA
 *
 * @param request The HttpServletRequest
 * @return/*from  w  ww  .  j  av a2  s. c o  m*/
 * @throws IOException
 * @throws ServletException
 */
private boolean doFilterPrincipal(HttpServletRequest request) throws IOException, ServletException {
    Principal principal = request.getUserPrincipal();
    if (principal == null) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            principal = (Principal) session.getAttribute(PRINCIPAL_SESSION_KEY);
        }
    }

    if (principal == null) {
        // no principal in this request
        return false;
    }

    if (IWAServiceDataHolder.getInstance().getProviders().isPrincipalException(request)) {
        // the providers signal to authenticate despite an existing principal, eg. NTLM post
        return false;
    }

    // user already authenticated

    if (principal instanceof WindowsPrincipal) {
        if (log.isDebugEnabled()) {
            log.debug("previously authenticated Windows user: " + principal.getName());
        }
        WindowsPrincipal windowsPrincipal = (WindowsPrincipal) principal;

        if (IWAServiceDataHolder.getInstance().isImpersonate() && windowsPrincipal.getIdentity() == null) {
            // This can happen when the session has been serialized then de-serialized
            // and because the IWindowsIdentity field is transient. In this case re-ask an
            // authentication to get a new identity.
            return false;
        }

        IWindowsImpersonationContext ctx = null;
        if (IWAServiceDataHolder.getInstance().isImpersonate()) {
            if (log.isDebugEnabled()) {
                log.debug("re-impersonating user");
            }
            ctx = windowsPrincipal.getIdentity().impersonate();
        }
        if (IWAServiceDataHolder.getInstance().isImpersonate() && ctx != null) {
            if (log.isDebugEnabled()) {
                log.debug("terminating impersonation");
            }
            ctx.revertToSelf();
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("previously authenticated user: " + principal.getName());
        }
    }
    return true;
}

From source file:org.rti.zcore.dar.struts.action.DeleteAdminRecordAction.java

/**
 * Deletes all admin records except user_info.
 * This assumes that an admin record has a null patient_id
 * @param mapping/*from  w w  w. jav  a 2  s .  c o  m*/
 * @param form
 * @param request
 * @param response
 * @return
 * @throws Exception
 * @deprecated - use zcore version instead.
 */
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    HttpSession session = request.getSession();
    Site site = SessionUtil.getInstance(session).getClientSettings().getSite();
    String siteAbbrev = site.getAbbreviation();
    Principal user = request.getUserPrincipal();
    String username = user.getName();
    Connection conn = null;
    ResultSet rs;

    StringBuffer sbuf = new StringBuffer();
    try {
        // using the super special root connection for this one mate!
        // conn = DatabaseUtils.getSpecialRootConnection(username);
        // use zeprs conn for derby
        conn = DatabaseUtils.getZEPRSConnection(username);
        try {
            rs = EncountersDAO.getAllEncounters(conn);
            String message = "";
            StringBuffer sbufLog = new StringBuffer();
            while (rs.next()) {
                Long encounterId = rs.getLong("id");
                Long formId = rs.getLong("form_id");
                String formName = DynaSiteObjects.getFormIdClassNameMap().get(formId);
                Long patientId = rs.getLong("patient_id");
                EncounterData vo = new EncounterData(); // dummy EncounterData is OK.
                if ((patientId == 0) && ((!formName.equals("UserInfo")) && (!formName.equals("ArtRegimen"))
                        && (!formName.equals("Item")) && (!formName.equals("ItemGroup"))
                        && (!formName.equals("RegimenGroup")) && (!formName.equals("Regimen"))
                        && (!formName.equals("RegimenItem_bridge")))) {
                    try {
                        PatientRecordUtils.deleteEncounter(conn, formId, encounterId, username, site, vo, null);
                    } catch (Exception e) {
                        request.setAttribute("exception", e);
                        return mapping.findForward("error");
                    }
                }
            }
            message = sbufLog.toString();
            request.setAttribute("message", message);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("exception", e);
            return mapping.findForward("error");
        } finally {
            //

        }

    } finally {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }
    return mapping.findForward("home");
}