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:cherry.foundation.springmvc.OperationLogHandlerInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

    Principal principal = request.getUserPrincipal();
    if (principal == null) {
        SecurityContext context = SecurityContextHolder.getContext();
        if (context != null) {
            principal = context.getAuthentication();
        }/*from  w  ww  .j a v a  2  s  .  com*/
    }
    if (principal != null) {
        MDC.put(LOGIN_ID, principal.getName());
    }

    StringBuilder builder = createBasicInfo(request);

    builder.append(" {");
    boolean first = true;
    for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {

        String key = entry.getKey();
        String lkey = key.toLowerCase();
        String[] val = entry.getValue();

        if (!first) {
            builder.append(", ");
        }
        first = false;
        builder.append(key).append(": ");
        if (lkey.contains("password")) {
            builder.append("<MASKED>");
        } else {
            builder.append(ToStringBuilder.reflectionToString(val, ToStringStyle.SIMPLE_STYLE));
        }

        for (int i = 0; i < paramPattern.size(); i++) {
            if (paramPattern.get(i).matcher(lkey).matches()) {
                if (val != null && val.length == 1) {
                    MDC.put(paramMdcKey.get(i), val[0]);
                } else {
                    MDC.put(paramMdcKey.get(i),
                            ToStringBuilder.reflectionToString(val, ToStringStyle.SIMPLE_STYLE));
                }
            }
        }
    }
    builder.append("}");

    loggerEnter.info(builder.toString());

    return true;
}

From source file:mobi.jenkinsci.server.core.servlet.HttpRequestDispatcherServlet.java

@Override
protected void service(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    try {/*from  w ww. ja  v a  2 s. c o  m*/
        final Account account = (Account) req.getUserPrincipal();

        final AbstractNode responseTree = pluginRequestDispatcher.getResponse(account, req);
        final String eTag = responseTree.getETag();
        final String reqETag = req.getHeader("If-None-Match");

        final Integer errorResponseStatus = errorStatusMap.get(responseTree.getClass());

        // Error response
        if (errorResponseStatus != null) {
            resp.sendError(errorResponseStatus);
        }

        // Cached response
        else if (reqETag != null && eTag != null && reqETag.equals(eTag)) {
            resp.setStatus(HttpStatus.SC_NOT_MODIFIED);
            log.debug("Resource " + req.getRequestURI() + " was NOT MODIFIED: returning HTTP-304");
        }

        // JSON response
        else {
            setResponseHeaders(resp, responseTree);
            resp.setHeader("Content-Type", "application/json");
            responseTree.toStream(resp.getOutputStream());
        }
    } catch (final ResourceNotFoundException e) {
        resp.sendError(HttpStatus.SC_NOT_FOUND);
    } catch (final Exception e) {
        throw new ServletException(e);
    }
}

From source file:com.pivotal.gemfire.tools.pulse.internal.service.ClusterRegionService.java

public JSONObject execute(final HttpServletRequest request) throws Exception {

    String userName = request.getUserPrincipal().getName();

    // get cluster object
    Cluster cluster = Repository.get().getCluster();

    // json object to be sent as response
    JSONObject responseJSON = new JSONObject();

    try {//from   ww w.  j a  v a2s  .c  o  m
        // getting cluster's Regions
        responseJSON.put("clusterName", cluster.getServerName());
        responseJSON.put("userName", userName);
        responseJSON.put("region", getRegionJson(cluster));
        responseJSON.put("connectedFlag", cluster.isConnectedFlag());
        responseJSON.put("connectedErrorMsg", cluster.getConnectionErrorMsg());
        // Send json response
        return responseJSON;
    } catch (JSONException e) {
        throw new Exception(e);
    }
}

From source file:co.cask.common.security.server.GrantAccessToken.java

private void grantToken(HttpServletRequest request, HttpServletResponse response, long tokenValidity)
        throws IOException, ServletException {

    String username = request.getUserPrincipal().getName();
    List<String> userGroups = Collections.emptyList();

    long issueTime = System.currentTimeMillis();
    long expireTime = issueTime + tokenValidity;
    // Create and sign a new AccessTokenIdentifier to generate the AccessToken.
    AccessTokenIdentifier tokenIdentifier = new AccessTokenIdentifier(username, userGroups, issueTime,
            expireTime);// w  w w  .  j a  v  a 2 s  .c  o m
    AccessToken token = tokenManager.signIdentifier(tokenIdentifier);
    LOG.debug("Issued token for user {}", username);

    // Set response headers
    response.setContentType("application/json;charset=UTF-8");
    response.addHeader("Cache-Control", "no-store");
    response.addHeader("Pragma", "no-cache");

    // Set response body
    JsonObject json = new JsonObject();
    byte[] encodedIdentifier = Base64.encodeBase64(tokenCodec.encode(token));
    json.addProperty(ExternalAuthenticationServer.ResponseFields.ACCESS_TOKEN,
            new String(encodedIdentifier, Charsets.UTF_8));
    json.addProperty(ExternalAuthenticationServer.ResponseFields.TOKEN_TYPE,
            ExternalAuthenticationServer.ResponseFields.TOKEN_TYPE_BODY);
    json.addProperty(ExternalAuthenticationServer.ResponseFields.EXPIRES_IN,
            TimeUnit.SECONDS.convert(tokenValidity, TimeUnit.MILLISECONDS));

    response.getOutputStream().print(json.toString());
    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:co.cask.cdap.security.server.GrantAccessToken.java

private void grantToken(HttpServletRequest request, HttpServletResponse response, long tokenValidity)
        throws IOException, ServletException {

    String username = request.getUserPrincipal().getName();
    List<String> userGroups = Collections.emptyList();

    long issueTime = System.currentTimeMillis();
    long expireTime = issueTime + tokenValidity;
    // Create and sign a new AccessTokenIdentifier to generate the AccessToken.
    AccessTokenIdentifier tokenIdentifier = new AccessTokenIdentifier(username, userGroups, issueTime,
            expireTime);/* w  w w  .  j a va 2 s.  c o m*/
    AccessToken token = tokenManager.signIdentifier(tokenIdentifier);
    LOG.debug("Issued token for user {}", username);

    // Set response headers
    response.setContentType("application/json;charset=UTF-8");
    response.addHeader(HttpHeaders.Names.CACHE_CONTROL, "no-store");
    response.addHeader(HttpHeaders.Names.PRAGMA, "no-cache");

    // Set response body
    JsonObject json = new JsonObject();
    byte[] encodedIdentifier = Base64.encodeBase64(tokenCodec.encode(token));
    json.addProperty(ExternalAuthenticationServer.ResponseFields.ACCESS_TOKEN,
            new String(encodedIdentifier, Charsets.UTF_8));
    json.addProperty(ExternalAuthenticationServer.ResponseFields.TOKEN_TYPE,
            ExternalAuthenticationServer.ResponseFields.TOKEN_TYPE_BODY);
    json.addProperty(ExternalAuthenticationServer.ResponseFields.EXPIRES_IN,
            TimeUnit.SECONDS.convert(tokenValidity, TimeUnit.MILLISECONDS));

    response.getOutputStream().print(json.toString());
    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:org.apache.roller.weblogger.ui.rendering.util.ParsedRequest.java

/**
 * Parse the given http request and extract any information we can.
 *
 * This abstract version of the constructor gathers info likely to be
 * relevant to all requests to Roller.//w  w  w .  java2 s  . co m
 */
public ParsedRequest(HttpServletRequest request) throws InvalidRequestException {

    // keep a reference to the original request
    this.request = request;

    // login status
    java.security.Principal prince = request.getUserPrincipal();
    if (prince != null) {
        this.authenticUser = prince.getName();
    }
    // set the detected type of the request
    deviceType = MobileDeviceRepository.getRequestType(request);
}

From source file:edu.nwpu.gemfire.monitor.service.ClusterSelectedRegionService.java

@Override
public ObjectNode execute(final HttpServletRequest request) throws Exception {

    String userName = request.getUserPrincipal().getName();
    String pulseData = request.getParameter("pulseData");
    JsonNode parameterMap = mapper.readTree(pulseData);
    String selectedRegionFullPath = parameterMap.get("ClusterSelectedRegion").get("regionFullPath").textValue();

    // get cluster object
    Cluster cluster = Repository.get().getCluster();

    // json object to be sent as response
    ObjectNode responseJSON = mapper.createObjectNode();

    // getting cluster's Regions
    responseJSON.put("clusterName", cluster.getServerName());
    responseJSON.put("userName", userName);
    responseJSON.put("selectedRegion", getSelectedRegionJson(cluster, selectedRegionFullPath));

    // Send json response
    return responseJSON;
}

From source file:org.nuxeo.ecm.webengine.jaxrs.login.AuthenticationFilter.java

@Override
public void run(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    LoginContext lc = null;/*from   www . ja v  a  2 s  .c om*/
    if (request.getUserPrincipal() == null) {
        try {
            lc = doLogin(request, response);
            request = wrapRequest(request, lc);
        } catch (LoginException e) {
            // login failed
            handleLoginFailure(request, response, e);
            return;
        }
    }

    try {
        chain.doFilter(request, response);
    } finally {
        ClientLoginModule.getThreadLocalLogin().clear();
        if (lc != null) {
            // a null lc may indicate an anonymous login
            try {
                lc.logout();
            } catch (LoginException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

From source file:org.atomserver.server.servlet.BlockingFilter.java

private boolean userNotBlocked(final HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    String name;//w  ww  . jav a2 s .c om
    Principal principal = request.getUserPrincipal();
    if (principal != null) {
        name = principal.getName();
        if (settings.getBlockedUsers().contains(name)) {
            String message = "USER IS BLOCKED :: (" + name + " is blocked from accessing the server.) :: "
                    + request.getRequestURI();
            setError(response, HttpServletResponse.SC_FORBIDDEN, message);
            return false;
        }
    }
    return true;
}

From source file:com.gae.LoginServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String thisURL = req.getRequestURI();
    resp.setContentType("text/html");
    UserService userService = UserServiceFactory.getUserService();
    PrintWriter pw = resp.getWriter();
    if (req.getUserPrincipal() == null) {
        pw.println("<a href=\"" + userService.createLoginURL(thisURL) + "\">Login</a>");
    } else {//from w  w  w.  jav  a  2s.c  o  m
        User user = userService.getCurrentUser();
        pw.println("<a href=\"" + userService.createLogoutURL(thisURL) + "\">Logout</a><br/>");
        pw.println("name = " + req.getUserPrincipal().getName() + "<br/>");
        pw.println("isAdmin = " + userService.isUserAdmin() + "<br/>");
        pw.println("domain = " + user.getAuthDomain() + "<br/>");
        pw.println("email = " + user.getEmail() + "<br/>");
        pw.println("nickname = " + user.getNickname() + "<br/>");
    }
}