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:fr.univlille2.ecm.platform.ui.web.auth.cas2.SecurityExceptionHandler.java

@Override
public void handleException(HttpServletRequest request, HttpServletResponse response, Throwable t)
        throws IOException, ServletException {

    @SuppressWarnings("deprecation")
    Throwable unwrappedException = unwrapException(t);
    log.debug("handleException#in");
    if (!ExceptionHelper.isSecurityError(unwrappedException)
            && !response.containsHeader(SSO_INITIAL_URL_REQUEST_KEY)) {
        super.handleException(request, response, t);
        return;/*  w  w w . j a  va  2 s.  c o m*/
    }

    Principal principal = request.getUserPrincipal();
    NuxeoPrincipal nuxeoPrincipal = null;
    if (principal instanceof NuxeoPrincipal) {
        nuxeoPrincipal = (NuxeoPrincipal) principal;
        // redirect to login than to requested page
        if (nuxeoPrincipal.isAnonymous()) {
            response.resetBuffer();

            String urlToReach = getURLToReach(request);
            log.debug(String.format("handleException#urlToReach#%s", urlToReach));
            Cookie cookieUrlToReach = new Cookie(NXAuthConstants.SSO_INITIAL_URL_REQUEST_KEY, urlToReach);
            cookieUrlToReach.setPath("/");
            cookieUrlToReach.setMaxAge(60);
            response.addCookie(cookieUrlToReach);
            log.debug(String.format("handleException#cookieUrlToReach#%s", cookieUrlToReach.getName()));
            if (!response.isCommitted()) {
                request.getRequestDispatcher(CAS_REDIRECTION_URL).forward(request, response);
            }
            FacesContext.getCurrentInstance().responseComplete();
        }
    }
    // go back to default handler
    super.handleException(request, response, t);
}

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

@RequestMapping(value = "/flow", method = RequestMethod.POST)
@ResponseBody/*from  w  w  w  .j a va 2  s.co  m*/
public String actionFlow(@RequestParam(required = true) String action,
        @RequestParam(required = false) String body, @RequestParam(required = true) String nodeId,
        HttpServletRequest request, @RequestParam(required = false) String container) {
    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";
    }

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

    FlowConfig flow = gson.fromJson(body, FlowConfig.class);

    Node node = Node.fromString(nodeId);
    flow.setNode(node);

    Status result = new Status(StatusCode.BADREQUEST, "Invalid request");
    if (action.equals("add")) {
        result = frm.addStaticFlow(flow);
        if (result.isSuccess()) {
            DaylightWebUtil.auditlog("Flow Entry", userName, "added",
                    flow.getName() + " on Node " + DaylightWebUtil.getNodeDesc(node, containerName, this),
                    containerName);
        }
    } else if (action.equals("edit")) {
        result = frm.modifyStaticFlow(flow);
        if (result.isSuccess()) {
            DaylightWebUtil.auditlog("Flow Entry", userName, "updated",
                    flow.getName() + " on Node " + DaylightWebUtil.getNodeDesc(node, containerName, this),
                    containerName);
        }
    }

    return (result.isSuccess()) ? StatusCode.SUCCESS.toString() : result.getDescription();
}

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

@SuppressWarnings("unchecked")
@RequestMapping(value = "/flow/deleteFlows", method = RequestMethod.POST)
@ResponseBody/*w w w . ja v a  2 s .c o m*/
public String removeSelectedFlows(@RequestParam(required = false) String body, HttpServletRequest request,
        @RequestParam(required = false) String container) {
    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";
    }
    IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper
            .getInstance(IForwardingRulesManager.class, containerName, this);
    if (frm == null) {
        return "Forwarding Rules Manager is not available";
    }

    List<Map<String, String>> flowList = new ArrayList<Map<String, String>>();
    flowList = gson.fromJson(body, flowList.getClass());
    Status result = new Status(StatusCode.BADREQUEST, "Invalid request");
    String status = "";
    for (Map<String, String> flowEntry : flowList) {
        Node node = Node.fromString(flowEntry.get("node"));
        result = frm.removeStaticFlow(flowEntry.get("name"), node);
        if (result.isSuccess()) {
            DaylightWebUtil.auditlog("Flow Entry", userName, "removed", flowEntry.get("name") + " on Node "
                    + DaylightWebUtil.getNodeDesc(node, containerName, this), containerName);
        } else {
            status = flowEntry.get("name") + ", " + status;
        }
    }
    if (!status.equals("")) {
        return "Could not remove " + status.substring(0, status.length() - 2) + " Flow(s)";
    } else {
        return "Success";
    }
}

From source file:dk.dma.msinm.user.security.SecurityServletFilter.java

/**
 * If the request contains a Basic authentication header, the user will be logged in for this request
 * using the specified credentials./*from   w w  w. ja  va  2  s  . c  om*/
 * <p>
 * If the authentication fails, this methods does nothing. It is left to the handler of the request,
 * say a Rest endpoint, to throw an error if security requirements are not met.
 *
 * @param request the servlet request
 * @return the request
 */
private HttpServletRequest attemptBasicAuthLogin(HttpServletRequest request) {
    try {
        String token = getAuthHeaderToken(request, BASIC_AUTH);
        if (token != null) {
            String[] cred = new String(Base64.getDecoder().decode(token), "UTF-8").split(":");
            request = SecurityUtils.login(userService, request, cred[0], cred[1]);
            log.trace("Found Basic Auth user " + request.getUserPrincipal().getName());
        }
    } catch (Exception ex) {
        request.setAttribute(AUTH_ERROR_ATTR, HttpServletResponse.SC_UNAUTHORIZED);
        log.warn("Failed logging in using Basic Authentication");
    }
    return request;
}

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

@RequestMapping(value = "/flow/{nodeId}/{name:.*}", method = RequestMethod.POST)
@ResponseBody/* w  w  w .  j  a  va 2s . c o m*/
public String removeFlow(@PathVariable("nodeId") String nodeId, @PathVariable("name") String name,
        @RequestParam(required = true) String action, HttpServletRequest request,
        @RequestParam(required = false) String container) {
    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";
    }

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

    Status result = null;
    Node node = Node.fromString(nodeId);
    if (node == null) {
        return null;
    }
    if (action.equals("remove")) {
        result = frm.removeStaticFlow(name, node);
        if (result.isSuccess()) {
            DaylightWebUtil.auditlog("Flow Entry", userName, "removed",
                    name + " on Node " + DaylightWebUtil.getNodeDesc(node, containerName, this), containerName);
        }
    } else if (action.equals("toggle")) {
        result = frm.toggleStaticFlowStatus(name, node);
        if (result.isSuccess()) {
            DaylightWebUtil.auditlog("Flow Entry", userName, "toggled",
                    name + " on Node " + DaylightWebUtil.getNodeDesc(node, containerName, this), containerName);
        }
    } else {
        result = new Status(StatusCode.BADREQUEST, "Unknown action");
    }

    return (result.isSuccess()) ? StatusCode.SUCCESS.toString() : result.getDescription();
}

From source file:com.sfs.dao.SAMLAuthenticationDAOImpl.java

/**
 * Load the UserBean from the SAML (CAS) response.
 *
 * @param userName the user name/*from w  w  w.  j a  v a 2  s. c o m*/
 * @param request the servlet request
 *
 * @return the user bean
 *
 * @throws SFSDaoException the SFS dao exception
 */
public final UserBean load(final String userName, final HttpServletRequest request) throws SFSDaoException {

    // Loads user details into bean using a supplied username
    if (userName == null) {
        throw new SFSDaoException("Username cannot be null");
    }
    if (userName.compareTo("") == 0) {
        throw new SFSDaoException("Username cannot be an empty string");
    }

    UserBean user = null;

    if (request != null && request.getUserPrincipal() != null) {

        final String username = request.getRemoteUser();

        if (StringUtils.isNotBlank(username)) {
            final AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();

            final Map<?, ?> attributes = principal.getAttributes();

            user = loadUserDetails(username, attributes);
        }
    }

    if (user == null) {
        throw new SFSDaoException("A user object for this username was not found");
    }
    return user;
}

From source file:com.streamsets.datacollector.restapi.LogResource.java

private boolean isJobAccessibleFromControlHub(HttpServletRequest request, String jobId) {
    String dpmBaseURL = config.get(RemoteSSOService.DPM_BASE_URL_CONFIG, "");
    if (dpmBaseURL.endsWith("/")) {
        dpmBaseURL = dpmBaseURL.substring(0, dpmBaseURL.length() - 1);
    }/*from  w  ww . ja v a 2s. c  o m*/

    // Get DPM user auth token from request cookie
    SSOPrincipal ssoPrincipal = (SSOPrincipal) request.getUserPrincipal();
    String userAuthToken = ssoPrincipal.getTokenStr();
    String componentId = runtimeInfo.getId();

    Response response = null;
    try {
        response = ClientBuilder.newClient().target(dpmBaseURL + "/jobrunner/rest/v1/job/" + jobId)
                .register(new CsrfProtectionFilter("CSRF")).request()
                .header(SSOConstants.X_USER_AUTH_TOKEN, userAuthToken).header(SSOConstants.X_REST_CALL, true)
                .get();
        if (response.getStatus() == Response.Status.OK.getStatusCode()) {
            return true;
        }
    } finally {
        if (response != null) {
            response.close();
        }
    }
    return false;
}

From source file:MyServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<HTML>");
    out.println("<HEAD>");
    out.println("<TITLE>");
    out.println("User Authentication");
    out.println("</TITLE>");
    out.println("</HEAD>");
    out.println("<BODY>");
    out.println("<H1>User Authentication</H1>");

    String type = request.getAuthType();
    out.println("Welcome to this secure page.<BR>");
    out.println("Authentication mechanism: " + type + "<BR>");
    Principal principal = request.getUserPrincipal();
    out.println("Your username is: " + principal.getName() + "<BR>");

    out.println("</BODY>");
    out.println("</HTML>");
}

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

@RequestMapping(value = "/node-flows")
@ResponseBody//from   w  ww  .  j a va  2s  . c o  m
public Map<String, Object> getNodeFlows(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;
    }
    IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper
            .getInstance(IForwardingRulesManager.class, containerName, this);
    if (frm == null) {
        return null;
    }

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

    for (Switch sw : switchManager.getNetworkDevices()) {
        Node node = sw.getNode();

        List<FlowConfig> flows = frm.getStaticFlows(node);

        String nodeDesc = node.toString();
        SwitchConfig config = switchManager.getSwitchConfig(node.toString());
        if ((config != null) && (config.getProperty(Description.propertyName) != null)) {
            nodeDesc = ((Description) config.getProperty(Description.propertyName)).getValue();
        }

        nodes.put(nodeDesc, flows.size());
    }

    return nodes;
}

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

@RequestMapping(value = "/main")
@ResponseBody//from www .jav a 2  s  . c om
public Map<String, Object> getFlows(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();
    Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
    if (privilege == Privilege.NONE) {
        return null;
    }

    // fetch frm
    IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper
            .getInstance(IForwardingRulesManager.class, containerName, this);
    if (frm == null) {
        return null;
    }

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

    // get static flow list
    List<FlowConfig> staticFlowList = frm.getStaticFlows();
    Set<Map<String, Object>> flowSet = new HashSet<Map<String, Object>>();
    for (FlowConfig flowConfig : staticFlowList) {
        Map<String, Object> entry = new HashMap<String, Object>();
        entry.put("flow", flowConfig);
        entry.put("name", flowConfig.getName());
        Node node = flowConfig.getNode();
        entry.put("node", getNodeDesc(node, switchManager));
        entry.put("nodeId", node.toString());
        flowSet.add(entry);
    }

    Map<String, Object> output = new HashMap<String, Object>(2);
    output.put("flows", flowSet);
    output.put("privilege", privilege);
    return output;
}