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.community.chest.gitcloud.facade.frontend.git.GitController.java

String authenticate(HttpServletRequest req) throws IOException {
    Principal principal = req.getUserPrincipal(); // check if already authenticated
    String username = (principal == null) ? null : principal.getName();
    if (!StringUtils.isEmpty(username)) {
        if (logger.isDebugEnabled()) {
            logger.debug("authenticate(" + req.getMethod() + ")[" + req.getRequestURI() + "]["
                    + req.getQueryString() + "]" + " using principal=" + username);
        }/*from   w w w .ja v a  2  s.  c o  m*/

        return username;
    }

    // TODO try to authenticate by cookie (if feature allowed) - see GitBlit#authenticate
    String authorization = StringUtils.trimToEmpty(req.getHeader(AUTH.WWW_AUTH_RESP));
    if (StringUtils.isEmpty(authorization)) {
        if (logger.isDebugEnabled()) {
            logger.debug("authenticate(" + req.getMethod() + ")[" + req.getRequestURI() + "]["
                    + req.getQueryString() + "] no authorization data");
        }
        return null;
    }

    // TODO add support for more authorization schemes - including password-less HTTP
    if (!authorization.startsWith(AuthSchemes.BASIC)) {
        logger.warn("authenticate(" + req.getMethod() + ")[" + req.getRequestURI() + "][" + req.getQueryString()
                + "]" + " unsupported authentication scheme: " + authorization);
        return null;
    }

    String b64Credentials = authorization.substring(AuthSchemes.BASIC.length()).trim();
    byte[] credBytes = Base64.decodeBase64(b64Credentials);
    String credentials = new String(credBytes, Charset.forName("UTF-8"));
    String[] credValues = StringUtils.split(credentials, ':');
    Validate.isTrue(credValues.length == 2, "Bad " + AuthSchemes.BASIC + " credentials format: %s",
            credentials);

    username = StringUtils.trimToEmpty(credValues[0]);
    String password = StringUtils.trimToEmpty(credValues[1]);
    if (authenticate(username, password)) {
        return username;
    } else {
        return null;
    }
}

From source file:org.opendaylight.controller.flows.web.Flows.java

@RequestMapping(value = "/node-ports")
@ResponseBody/*from  ww w.  j ava2  s  .  c  o  m*/
public Map<String, Object> getNodePorts(HttpServletRequest request,
        @RequestParam(required = false) String container) {
    String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;

    // Derive the privilege this user has on the current container
    String userName = request.getUserPrincipal().getName();
    if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) == Privilege.NONE) {
        return null;
    }

    ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class,
            containerName, this);
    if (switchManager == null) {
        return null;
    }

    Map<String, Object> nodes = new HashMap<String, Object>();
    Map<String, String> port;

    for (Switch node : switchManager.getNetworkDevices()) {
        port = new HashMap<String, String>(); // new port
        Set<NodeConnector> nodeConnectorSet = node.getNodeConnectors();

        if (nodeConnectorSet != null) {
            for (NodeConnector nodeConnector : nodeConnectorSet) {
                String nodeConnectorName = ((Name) switchManager.getNodeConnectorProp(nodeConnector,
                        Name.NamePropName)).getValue();
                port.put(nodeConnector.getID().toString(),
                        nodeConnectorName + "(" + nodeConnector.getNodeConnectorIDString() + ")");
            }
        }

        // add ports
        Map<String, Object> entry = new HashMap<String, Object>();
        entry.put("ports", port);

        // add name
        entry.put("name", getNodeDesc(node.getNode(), switchManager));

        // add to the node
        nodes.put(node.getNode().toString(), entry);
    }

    return nodes;
}

From source file:org.apache.hadoop.hdfs.server.namenode.ImageServlet.java

private void validateRequest(ServletContext context, Configuration conf, HttpServletRequest request,
        HttpServletResponse response, FSImage nnImage, String theirStorageInfoString) throws IOException {

    if (UserGroupInformation.isSecurityEnabled()
            && !isValidRequestor(context, request.getUserPrincipal().getName(), conf)) {
        String errorMsg = "Only Namenode, Secondary Namenode, and administrators may access " + "this servlet";
        response.sendError(HttpServletResponse.SC_FORBIDDEN, errorMsg);
        LOG.warn("Received non-NN/SNN/administrator request for image or edits from "
                + request.getUserPrincipal().getName() + " at " + request.getRemoteHost());
        throw new IOException(errorMsg);
    }//  w ww  .ja  v a  2s . c  o  m

    String myStorageInfoString = nnImage.getStorage().toColonSeparatedString();
    if (theirStorageInfoString != null && !myStorageInfoString.equals(theirStorageInfoString)) {
        String errorMsg = "This namenode has storage info " + myStorageInfoString
                + " but the secondary expected " + theirStorageInfoString;
        response.sendError(HttpServletResponse.SC_FORBIDDEN, errorMsg);
        LOG.warn("Received an invalid request file transfer request " + "from a secondary with storage info "
                + theirStorageInfoString);
        throw new IOException(errorMsg);
    }
}

From source file:org.apache.cxf.fediz.example.FederationServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head><title>WS Federation Tomcat Examples</title></head>");
    out.println("<body>");
    out.println("<h1>Hello World</h1>");
    out.println("Hello world<br>");
    out.println("Request url: " + request.getRequestURL().toString() + "<p>");

    out.println("<br><b>User</b><p>");
    Principal p = request.getUserPrincipal();
    if (p != null) {
        out.println("Principal: " + p.getName() + "<p>");
    }/*from  w  w w.  j  a  v  a2s.c  om*/

    out.println("<br><b>Roles</b><p>");
    List<String> roleListToCheck = Arrays.asList("Admin", "Manager", "User", "Authenticated");
    for (String item : roleListToCheck) {
        out.println("Has role '" + item + "': " + ((request.isUserInRole(item)) ? "<b>yes</b>" : "no") + "<p>");
    }

    if (p instanceof FederationPrincipal) {
        FederationPrincipal fp = (FederationPrincipal) p;

        out.println("<br><b>Claims</b><p>");
        ClaimCollection claims = fp.getClaims();
        for (Claim c : claims) {
            out.println(c.getClaimType().toString() + ": " + c.getValue() + "<p>");
        }
    } else {
        out.println("Principal is not instance of FederationPrincipalImpl");
    }

    Greeter service = (Greeter) ApplicationContextProvider.getContext().getBean("HelloServiceClient");
    String reply = service.greetMe();

    out.println("<br><b>Greeter Service Response: " + reply + "</b><p>");

    out.println("</body>");
}

From source file:com.esri.gpt.control.arcims.ServletConnectorProxy.java

/**
 * Handles a GET request. <p/> The default behavior is the execute the doGet
 * method./*from w  ww .  j a  v a2  s. c o  m*/
 * 
 * @param request
 *          the servlet request
 * @param response
 *          the servlet response
 * @throws ServletException
 * @throws IOException
 *           if an exception occurs
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    /* if(true){
       doPost(request,response);
       return;
     }*/

    /*if(!_redirectURL.startsWith("http"))
       setURL(request);
            
    response.sendRedirect(_redirectURL + "?" + request.getQueryString());*/

    Principal p = request.getUserPrincipal();
    if (p != null) {
        LOGGER.finer("UserName : " + p.getName());
    }

    LOGGER.finer("Query string=" + request.getQueryString());
    if ("ping".equalsIgnoreCase(request.getParameter("Cmd"))) {
        response.getWriter().write("IMS v9.3.0");
    } else if ("ping".equalsIgnoreCase(request.getParameter("cmd"))) {
        response.getWriter().write("IMS v9.3.0");
    } else if ("getVersion".equalsIgnoreCase(request.getParameter("Cmd"))) {
        response.getWriter().write("Version=9.3.0\nBuild_Number=514.2159");
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:org.structr.web.auth.HttpAuthenticator.java

@Override
public void checkResourceAccess(HttpServletRequest request, String resourceSignature, String propertyView)
        throws FrameworkException {

    logger.log(Level.FINE, "Got session? ", request.getSession(false));
    logger.log(Level.FINE, "User principal: ", request.getUserPrincipal());

}

From source file:com.icesoft.faces.webapp.http.servlet.ServletEnvironmentRequest.java

public ServletEnvironmentRequest(Object request, HttpSession session, Authorization authorization) {
    HttpServletRequest initialRequest = (HttpServletRequest) request;
    this.session = session;
    this.authorization = authorization;
    //Copy common data
    authType = initialRequest.getAuthType();
    contextPath = initialRequest.getContextPath();
    remoteUser = initialRequest.getRemoteUser();
    userPrincipal = initialRequest.getUserPrincipal();
    requestedSessionId = initialRequest.getRequestedSessionId();
    requestedSessionIdValid = initialRequest.isRequestedSessionIdValid();

    attributes = new HashMap();
    Enumeration attributeNames = initialRequest.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
        String name = (String) attributeNames.nextElement();
        Object attribute = initialRequest.getAttribute(name);
        if ((null != name) && (null != attribute)) {
            attributes.put(name, attribute);
        }/*w  w w  . ja va 2  s .  co  m*/
    }

    // Warning:  For some reason, the various javax.include.* attributes are
    // not available via the getAttributeNames() call.  This may be limited
    // to a Liferay issue but when the MainPortlet dispatches the call to
    // the MainServlet, all of the javax.include.* attributes can be
    // retrieved using this.request.getAttribute() but they do NOT appear in
    // the Enumeration of names returned by getAttributeNames().  So here
    // we manually add them to our map to ensure we can find them later.
    String[] incAttrKeys = Constants.INC_CONSTANTS;
    for (int index = 0; index < incAttrKeys.length; index++) {
        String incAttrKey = incAttrKeys[index];
        Object incAttrVal = initialRequest.getAttribute(incAttrKey);
        if (incAttrVal != null) {
            attributes.put(incAttrKey, initialRequest.getAttribute(incAttrKey));
        }
    }

    headers = new HashMap();
    Enumeration headerNames = initialRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = (String) headerNames.nextElement();
        Enumeration values = initialRequest.getHeaders(name);
        headers.put(name, Collections.list(values));
    }

    parameters = new HashMap();
    Enumeration parameterNames = initialRequest.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String name = (String) parameterNames.nextElement();
        parameters.put(name, initialRequest.getParameterValues(name));
    }

    scheme = initialRequest.getScheme();
    serverName = initialRequest.getServerName();
    serverPort = initialRequest.getServerPort();
    secure = initialRequest.isSecure();

    //Copy servlet specific data
    cookies = initialRequest.getCookies();
    method = initialRequest.getMethod();
    pathInfo = initialRequest.getPathInfo();
    pathTranslated = initialRequest.getPathTranslated();
    queryString = initialRequest.getQueryString();
    requestURI = initialRequest.getRequestURI();
    try {
        requestURL = initialRequest.getRequestURL();
    } catch (NullPointerException e) {
        //TODO remove this catch block when GlassFish bug is addressed
        if (log.isErrorEnabled()) {
            log.error("Null Protocol Scheme in request", e);
        }
        HttpServletRequest req = initialRequest;
        requestURL = new StringBuffer(
                "http://" + req.getServerName() + ":" + req.getServerPort() + req.getRequestURI());
    }
    servletPath = initialRequest.getServletPath();
    servletSession = initialRequest.getSession();
    isRequestedSessionIdFromCookie = initialRequest.isRequestedSessionIdFromCookie();
    isRequestedSessionIdFromURL = initialRequest.isRequestedSessionIdFromURL();
    characterEncoding = initialRequest.getCharacterEncoding();
    contentLength = initialRequest.getContentLength();
    contentType = initialRequest.getContentType();
    protocol = initialRequest.getProtocol();
    remoteAddr = initialRequest.getRemoteAddr();
    remoteHost = initialRequest.getRemoteHost();
    initializeServlet2point4Properties(initialRequest);
}

From source file:org.apache.cxf.fediz.example.FederationServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head><title>WS Federation Tomcat Examples</title></head>");
    out.println("<body>");
    out.println("<h1>Hello World</h1>");
    out.println("Hello world<br>");
    out.println("Request url: " + request.getRequestURL().toString() + "<p>");

    out.println("<br><b>User</b><p>");
    Principal p = request.getUserPrincipal();
    if (p != null) {
        out.println("Principal: " + p.getName() + "<p>");
    }//  w w w .  ja v a  2  s.c o  m

    out.println("<br><b>Roles</b><p>");
    List<String> roleListToCheck = Arrays.asList("Admin", "Manager", "User", "Authenticated");
    for (String item : roleListToCheck) {
        out.println("Has role '" + item + "': " + ((request.isUserInRole(item)) ? "<b>yes</b>" : "no") + "<p>");
    }

    if (p instanceof FederationPrincipal) {
        FederationPrincipal fp = (FederationPrincipal) p;

        out.println("<br><b>Claims</b><p>");
        ClaimCollection claims = fp.getClaims();
        for (Claim c : claims) {
            out.println(c.getClaimType().toString() + ": " + c.getValue() + "<p>");
        }
    } else {
        out.println("Principal is not instance of FederationPrincipal");
    }

    Element el = SecurityTokenThreadLocal.getToken();
    if (el != null) {
        out.println("<p>Bootstrap token...");
        String token = null;
        try {
            TransformerFactory transFactory = TransformerFactory.newInstance();
            Transformer transformer = transFactory.newTransformer();
            StringWriter buffer = new StringWriter();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.transform(new DOMSource(el), new StreamResult(buffer));
            token = buffer.toString();
            out.println("<p>" + StringEscapeUtils.escapeXml(token));
        } catch (Exception ex) {
            out.println("<p>Failed to transform cached element to string: " + ex.toString());
        }
    } else {
        out.println("<p>Bootstrap token not cached in thread local storage");
    }

    out.println("</body>");
}

From source file:org.opendaylight.controller.flows.web.Flows.java

@RequestMapping(value = "/valid-flows/{nodeId}")
@ResponseBody//from  ww  w. j a v  a2 s  .c  o m
public Object getValidActions(HttpServletRequest request, @RequestParam(required = false) String container,
        @PathVariable("nodeId") String nodeId) {
    String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;

    // Authorization check
    String userName = request.getUserPrincipal().getName();
    if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
        return "Operation not authorized";
    }

    ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class,
            containerName, this);
    if (switchManager == null) {
        return null;
    }

    Map<String, String> result = new TreeMap<String, String>();

    Node node = Node.fromString(nodeId);
    SupportedFlowActions supportedFlows = (SupportedFlowActions) switchManager.getNodeProp(node,
            "supportedFlowActions");
    List<Class<? extends Action>> actions = supportedFlows.getActions();
    for (Class<? extends Action> action : actions) {
        String actionName = action.getSimpleName().toLowerCase();
        if (actionCompare(actionName, ActionType.DROP)) {
            result.put(ActionType.DROP.toString(), "Drop");
        } else if (actionCompare(actionName, ActionType.LOOPBACK)) {
            result.put(ActionType.LOOPBACK.toString(), "Loopback");
        } else if (actionCompare(actionName, ActionType.FLOOD)) {
            result.put(ActionType.FLOOD.toString(), "Flood");
        } else if (actionCompare(actionName, ActionType.FLOOD_ALL)) {
            result.put(ActionType.FLOOD_ALL.toString(), "Flood All");
        } else if (actionCompare(actionName, ActionType.CONTROLLER)) {
            result.put(ActionType.CONTROLLER.toString(), "Controller");
        } else if (actionCompare(actionName, ActionType.INTERFACE)) {
            result.put(ActionType.INTERFACE.toString(), "Interface");
        } else if (actionCompare(actionName, ActionType.SW_PATH)) {
            result.put(ActionType.SW_PATH.toString(), "Software Path");
        } else if (actionCompare(actionName, ActionType.HW_PATH)) {
            result.put(ActionType.HW_PATH.toString(), "Hardware Path");
        } else if (actionCompare(actionName, ActionType.OUTPUT)) {
            result.put(ActionType.OUTPUT.toString(), "Output");
        } else if (actionCompare(actionName, ActionType.ENQUEUE)) {
            result.put(ActionType.ENQUEUE.toString(), "Enqueue");
        } else if (actionCompare(actionName, ActionType.SET_DL_SRC)) {
            result.put(ActionType.SET_DL_SRC.toString(), "Set Datalayer Source Address");
        } else if (actionCompare(actionName, ActionType.SET_DL_DST)) {
            result.put(ActionType.SET_DL_DST.toString(), "Set Datalayer Destination Address");
        } else if (actionCompare(actionName, ActionType.SET_VLAN_ID)) {
            result.put(ActionType.SET_VLAN_ID.toString(), "Set VLAN ID");
        } else if (actionCompare(actionName, ActionType.SET_VLAN_PCP)) {
            result.put(ActionType.SET_VLAN_PCP.toString(), "Set VLAN Priority");
        } else if (actionCompare(actionName, ActionType.SET_VLAN_CFI)) {
            result.put(ActionType.SET_VLAN_CFI.toString(), "Set VLAN CFI");
        } else if (actionCompare(actionName, ActionType.POP_VLAN)) {
            result.put(ActionType.POP_VLAN.toString(), "Pop VLAN");
        } else if (actionCompare(actionName, ActionType.PUSH_VLAN)) {
            result.put(ActionType.PUSH_VLAN.toString(), "Push VLAN");
        } else if (actionCompare(actionName, ActionType.SET_DL_TYPE)) {
            result.put(ActionType.SET_DL_TYPE.toString(), "Set EtherType");
        } else if (actionCompare(actionName, ActionType.SET_NW_SRC)) {
            result.put(ActionType.SET_NW_SRC.toString(), "Set Network Source Address");
        } else if (actionCompare(actionName, ActionType.SET_NW_DST)) {
            result.put(ActionType.SET_NW_DST.toString(), "Set Network Destination Address");
        } else if (actionCompare(actionName, ActionType.SET_NW_TOS)) {
            result.put(ActionType.SET_NW_TOS.toString(), "Modify ToS Bits");
        } else if (actionCompare(actionName, ActionType.SET_TP_SRC)) {
            result.put(ActionType.SET_TP_SRC.toString(), "Modify Transport Source Port");
        } else if (actionCompare(actionName, ActionType.SET_TP_DST)) {
            result.put(ActionType.SET_TP_DST.toString(), "Modify Transport Destination Port");
        } else if (actionCompare(actionName, ActionType.SET_NEXT_HOP)) {
            result.put(ActionType.SET_NEXT_HOP.toString(), "Set Next Hop");
        }
    }

    return result;
}