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:org.jboss.bpm.console.server.UserMgmtFacade.java

@GET
@Path("user/roles")
@Produces("application/json")
public Response getRolesForJAASPrincipal(@Context HttpServletRequest request,
        @QueryParam("roleCheck") String roleCheck) {
    // TODO: Why not use the identity DB right away?
    // These roles are security roles
    if (null == roleCheck)
        throw new WebApplicationException(new IllegalArgumentException("Missing parameter 'roleCheck'"));

    log.debug("Role check user: " + request.getUserPrincipal().getName() + ", actualRoles requested: "
            + roleCheck);/*from  ww w  .ja  v a  2s.  c o  m*/

    List<RoleAssignmentRef> actualRoles = new ArrayList<RoleAssignmentRef>();

    StringTokenizer tok = new StringTokenizer(roleCheck, ",");
    while (tok.hasMoreTokens()) {
        String possibleRole = tok.nextToken();
        actualRoles.add(new RoleAssignmentRef(possibleRole, request.isUserInRole(possibleRole)));
    }
    return createJsonResponse(new RoleAssignmentRefWrapper(actualRoles));
}

From source file:org.picketlink.test.trust.servlet.GatewayServlet.java

private void authInfoAction(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    PrintWriter out = resp.getWriter();
    out.println("GatewayAuthentication=Success");
    out.println("ClassName=" + this.getClass().getName());
    out.println("--------------------------------------");

    out.println("UserPrincipal=" + req.getUserPrincipal().getName());
    out.println("--------------------------------------");

    Subject subject = SecurityAssociation.getSubject();
    if (subject != null) {
        out.println("Subject=" + subject);
        out.println("--------------------------------------");
        out.println("PublicCredentialsSize=" + subject.getPublicCredentials().size());
        out.println("--------------------------------------");
        int i = 0;
        for (Object c : subject.getPublicCredentials()) {
            out.println("Credential[" + i + "]=" + c.toString());
            i++;//from w w  w. j a va  2 s  .c  o m
        }
    }
}

From source file:com.yoshio3.modules.AzureADServerAuthModule.java

public boolean getSessionPrincipal(HttpServletRequest request) {
    return request.getUserPrincipal() != null;
    //        return (AzureADUserPrincipal) request.getSession().getAttribute(PRINCIPAL_SESSION_NAME);
}

From source file:com.betfair.tornjak.monitor.overlay.AuthUtilsTest.java

@Test
public void testNotAuthenticated() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    ServletContext context = mock(ServletContext.class);

    when(context.getAttribute("com.betfair.tornjak.monitor.overlay.RolePerms"))
            .thenReturn(new AuthBuilder().role("jmxadmin").allow(".*:.*:.*").getRolePerms());
    when(request.getUserPrincipal()).thenReturn(null);

    Auth auth = AuthUtils.checkAuthorised(request, response, context);
    assertThat("User should not be authorised", auth, nullValue());

    verify(response, times(1)).sendError(HttpServletResponse.SC_UNAUTHORIZED);
    verifyNoMoreInteractions(response);/* ww w .  j av  a 2  s. c om*/
}

From source file:org.eurekaclinical.user.service.resource.UserResource.java

/**
 * Changes a user's password./*from   w  w w  . j  a v  a 2s .c  o  m*/
 *
 * @param request the incoming servlet request
 * @param passwordChangeRequest the request to use to make the password
 * change
 * @return the response.
 *
 * @throws HttpStatusException Thrown when a password cannot be properly
 * hashed, or the passwords are mismatched.
 */
@RolesAllowed({ "researcher", "admin" })
@Path("/passwordchange")
@POST
public Response changePassword(@Context HttpServletRequest request,
        PasswordChangeRequest passwordChangeRequest) {
    String username = request.getUserPrincipal().getName();
    LocalUserEntity user = this.localUserDao.getByName(username);
    Response response = null;

    if (user == null) {
        throw new HttpStatusException(Response.Status.NOT_FOUND);
    }

    String newPassword = passwordChangeRequest.getNewPassword();
    String oldPasswordHash;
    String newPasswordHash;
    try {
        oldPasswordHash = StringUtil.md5(passwordChangeRequest.getOldPassword());
        newPasswordHash = StringUtil.md5(newPassword);

    } catch (NoSuchAlgorithmException e) {
        LOGGER.error(e.getMessage(), e);
        throw new HttpStatusException(Response.Status.INTERNAL_SERVER_ERROR, e);
    }

    if (user.getPassword().equals(oldPasswordHash)) {
        user.setPassword(newPasswordHash);
        user.setPasswordExpiration(this.getExpirationDate());
        this.localUserDao.update(user);

        try {
            this.emailSender.sendPasswordChangeMessage(user);
            response = Response.status(Status.NO_CONTENT).build();
        } catch (EmailException ee) {
            LOGGER.error(ee.getMessage(), ee);
        }
    } else {
        throw new HttpStatusException(Response.Status.BAD_REQUEST,
                "Error while changing password. Old password is incorrect.");
    }
    return response;
}

From source file:it.govpay.web.filters.SessionTimeoutFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        //   HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        String requestPath = httpServletRequest.getRequestURI();
        this.log.debug("Richiesta risorsa: " + requestPath);

        String principal = null;//from  w  w w.  j  av  a 2 s  .c  o m
        if (httpServletRequest.getUserPrincipal() != null) {
            principal = httpServletRequest.getUserPrincipal().getName();
        }

        this.log.debug("Utente: " + principal);

        // is session expire control required for this request?
        if (this.isSessionControlRequiredForThisResource(httpServletRequest)) {
            HttpSession sessione = httpServletRequest.getSession(false);

            this.log.debug("Session: " + (sessione != null ? sessione.getId() : "Null"));

            // is session invalid?
            if (this.isSessionInvalid(httpServletRequest)) {
                //String redirPageUrl = httpServletRequest.getContextPath() + "/";

                if (sessione != null)
                    sessione.invalidate();

                this.log.debug("La sessione non e' valida, effettuo redirect...");

                //se la pagina richiesta e' quella di login allora redirigo direttamente a quella, altrimenti a quella di timeout
                //redirPageUrl += StringUtils.contains(httpServletRequest.getRequestURI(), getLoginPage()) ? getLoginPage() : getTimeoutPage();
                //   redirPageUrl += getRedirPage(httpServletRequest);
                //               log.info("session is invalid! redirecting to page : " + redirPageUrl);
                //httpServletResponse.sendRedirect(redirPageUrl);
                //return;
            }
        }
    }
    filterChain.doFilter(request, response);

}

From source file:org.nuxeo.ecm.tokenauth.servlet.TokenAuthenticationServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // Don't provide token for anonymous user unless 'allowAnonymous' parameter is explicitly set to true in
    // the authentication plugin configuration
    Principal principal = req.getUserPrincipal();
    if (principal instanceof NuxeoPrincipal && ((NuxeoPrincipal) principal).isAnonymous()) {
        PluggableAuthenticationService authenticationService = (PluggableAuthenticationService) Framework
                .getRuntime().getComponent(PluggableAuthenticationService.NAME);
        AuthenticationPluginDescriptor tokenAuthPluginDesc = authenticationService
                .getDescriptor(TOKEN_AUTH_PLUGIN_NAME);
        if (tokenAuthPluginDesc == null || !(Boolean
                .valueOf(tokenAuthPluginDesc.getParameters().get(TokenAuthenticator.ALLOW_ANONYMOUS_KEY)))) {
            log.debug("Anonymous user is not allowed to acquire an authentication token.");
            resp.sendError(HttpStatus.SC_UNAUTHORIZED);
            return;
        }//from   w w w.j av  a  2 s  . c o m

    }

    // Get request parameters
    String applicationName = req.getParameter(APPLICATION_NAME_PARAM);
    String deviceId = req.getParameter(DEVICE_ID_PARAM);
    String deviceDescription = req.getParameter(DEVICE_DESCRIPTION_PARAM);
    String permission = req.getParameter(PERMISSION_PARAM);
    String revokeParam = req.getParameter(REVOKE_PARAM);
    boolean revoke = Boolean.valueOf(revokeParam);

    // If one of the required parameters is null or empty, send an
    // error with the 400 status
    if (!revoke && (StringUtils.isEmpty(applicationName) || StringUtils.isEmpty(deviceId)
            || StringUtils.isEmpty(permission))) {
        log.error(
                "The following request parameters are mandatory to acquire an authentication token: applicationName, deviceId, permission.");
        resp.sendError(HttpStatus.SC_BAD_REQUEST);
        return;
    }
    if (revoke && (StringUtils.isEmpty(applicationName) || StringUtils.isEmpty(deviceId))) {
        log.error(
                "The following request parameters are mandatory to revoke an authentication token: applicationName, deviceId.");
        resp.sendError(HttpStatus.SC_BAD_REQUEST);
        return;
    }

    // Decode parameters
    applicationName = URIUtil.decode(applicationName);
    deviceId = URIUtil.decode(deviceId);
    if (!StringUtils.isEmpty(deviceDescription)) {
        deviceDescription = URIUtil.decode(deviceDescription);
    }
    if (!StringUtils.isEmpty(permission)) {
        permission = URIUtil.decode(permission);
    }

    // Get user name from request Principal
    if (principal == null) {
        resp.sendError(HttpStatus.SC_UNAUTHORIZED);
        return;
    }
    String userName = principal.getName();

    // Write response
    String response = null;
    int statusCode;
    TokenAuthenticationService tokenAuthService = Framework.getLocalService(TokenAuthenticationService.class);
    try {
        // Token acquisition: acquire token and write it to the response
        // body
        if (!revoke) {
            response = tokenAuthService.acquireToken(userName, applicationName, deviceId, deviceDescription,
                    permission);
            statusCode = 201;
        }
        // Token revocation
        else {
            String token = tokenAuthService.getToken(userName, applicationName, deviceId);
            if (token == null) {
                response = String.format(
                        "No token found for userName %s, applicationName %s and deviceId %s; nothing to do.",
                        userName, applicationName, deviceId);
                statusCode = 400;
            } else {
                tokenAuthService.revokeToken(token);
                response = String.format("Token revoked for userName %s, applicationName %s and deviceId %s.",
                        userName, applicationName, deviceId);
                statusCode = 202;
            }
        }
        sendTextResponse(resp, response, statusCode);
    } catch (TokenAuthenticationException e) {
        // Should never happen as parameters have already been checked
        resp.sendError(HttpStatus.SC_NOT_FOUND);
    }
}

From source file:be.fedict.hsm.admin.webapp.security.AuthenticationController.java

public void login(ComponentSystemEvent event) {
    LOG.debug("login");
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (facesContext.getResponseComplete()) {
        return;/* ww w .  j  a v a 2 s. c o m*/
    }
    if (null == this.authenticationCertificate) {
        /*
         * Caused by a direct navigation to post-login.jsf
         */
        redirect(facesContext, "/index.xhtml");
        return;
    }
    byte[] encodedCertificate;
    try {
        encodedCertificate = this.authenticationCertificate.getEncoded();
    } catch (CertificateEncodingException e) {
        LOG.error("certificate encoding error: " + e.getMessage(), e);
        return;
    }
    /*
     * The challenged certificate is the unique user identifier.
     */
    String username = DigestUtils.sha1Hex(encodedCertificate);
    String password = this.identity.getCardNumber();
    ExternalContext externalContext = facesContext.getExternalContext();
    HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
    try {
        httpServletRequest.login(username, password);
    } catch (ServletException e) {
        LOG.error("login error: " + e.getMessage(), e);
        accessDenied(facesContext);
        return;
    }
    Principal userPrincipal = httpServletRequest.getUserPrincipal();
    if (null == userPrincipal) {
        accessDenied(facesContext);
        return;
    }
    LOG.debug("user principal: " + userPrincipal.getName());
    LOG.debug("admin role: " + httpServletRequest.isUserInRole(AdministratorRoles.ADMINISTRATOR));
    if (false == httpServletRequest.isUserInRole(AdministratorRoles.ADMINISTRATOR)) {
        accessDenied(facesContext);
        return;
    }
    String targetViewId = SecurityPhaseListener.getTargetViewId(externalContext);
    redirect(facesContext, targetViewId);
}

From source file:org.eclipse.skalli.core.permit.PermitComponent.java

@Override
public String login(HttpServletRequest request, Project project) {
    String userId = null;/*from w  w  w  .  ja v  a  2s .c  om*/
    Principal userPrincipal = request.getUserPrincipal();
    if (userPrincipal != null) {
        userId = userPrincipal.getName();
        if (StringUtils.isNotBlank(userId)) {
            userId = userId.toLowerCase(Locale.ENGLISH);
        }
    }
    HttpSession session = request.getSession();
    PermitSet permits = getSessionPermits(session, userId, project);
    if (permits == null) {
        permits = getPermits(userId, project);
        setSessionPermits(session, permits, project);
    }
    threadUserId.set(userId);
    threadProject.set(project);
    threadPermits.set(permits);
    return userId;
}

From source file:uk.ac.ebi.metabolights.controller.SubmissionQueueController.java

@RequestMapping(value = { "/submittoqueue" })
public ModelAndView preSubmit(HttpServletRequest request) {
    MetabolightsUser user = null;//from ww w  . java 2 s  . c  o m

    ModelAndView mav = AppContext.getMAVFactory().getFrontierMav("submittoqueue"); // Call the Submission form page
    if (request.getUserPrincipal() != null)
        user = (MetabolightsUser) (SecurityContextHolder.getContext().getAuthentication().getPrincipal());

    if (user != null) {
        //mav.addObject("user", user);
        try {
            mav.addObject("queueditems", SubmissionQueue.getQueuedForUserId(user.getUserName().toString()));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // If the user is a curator
        if (user.isCurator()) {
            mav.addObject("users", userService.getAll());
        }
    }

    return mav;
}