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.ala.spatial.services.utils.Utilities.java

public static String getUserEmail(HttpServletRequest req) {
    String useremail = DEFAULT_USER_EMAIL;
    try {// w ww  . j  a  va2 s .c o  m
        //System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        //System.out.println("Breakdown Authentication details");
        if (req.getUserPrincipal() != null) {
            Principal principal = req.getUserPrincipal();
            if (principal instanceof AttributePrincipal) {
                AttributePrincipal ap = (AttributePrincipal) principal;
                //System.out.println("ap: " + ap.getAttributes().toString());
                useremail = (String) ap.getAttributes().get("email");
            } else {
                useremail = principal.getName();
            }
        }
        //System.out.println("useremail: " + useremail);
        //System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");

    } catch (Exception e) {
        System.out.println("No user available");
    }

    return useremail;
}

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

/**
 * Attempts to log-in the user.//from   w  w  w  .j a  v  a 2 s.com
 * <p>
 * The web-app is using a custom login-module, {@linkplain JbossLoginModule}, and the
 * natural solution would be that this module set the {@code User} as the user principal
 * upon successful authentication.
 * <br>
 * However, this tends to cause ClassCastException's when the web-app has been reloaded,
 * because a different class-loader is used for the login-modules.
 * <br>
 * Hence, the login-module sets a {@code SimplePrincipal} as the request user principal, and this
 * method swaps the {@code SimplePrincipal} for a {@code User} principal.
 *
 * @param userService the user service
 * @param request the servlet request
 * @param username the user name
 * @param password the password
 * @return the updated request
 */
public static HttpServletRequest login(UserService userService, HttpServletRequest request, String username,
        String password) throws ServletException {
    // Will throw an exception if the login fails
    //request.logout();
    request.login(username, password);

    // The email is used as it is unique for the user
    String email = request.getUserPrincipal().getName();
    final User user = userService.findByEmail(email);
    return new HttpServletRequestWrapper(request) {
        @Override
        public java.security.Principal getUserPrincipal() {
            return user;
        }
    };
}

From source file:org.tightblog.rendering.requests.WeblogRequest.java

static void parseRequest(WeblogRequest wreq, HttpServletRequest sreq) {
    wreq.request = sreq;//ww  w .  ja  va 2  s  .  com
    wreq.queryString = sreq.getQueryString();
    wreq.deviceType = Utilities.getDeviceType(sreq);

    // login status
    java.security.Principal principal = sreq.getUserPrincipal();
    if (principal != null) {
        wreq.authenticatedUser = principal.getName();
    }

    // servlet path: /tb-ui/rendering/(page|feed|mediafile|comment|search)/weblogHandle[/extrainfo]*
    String path = sreq.getServletPath();

    log.debug("parsing path {}", path);

    // first extract the weblog handle
    if (StringUtils.isNotBlank(path)) {

        // strip off the leading slash
        path = path.substring(1);

        String[] pathElements = path.split("/", 5);

        wreq.weblogHandle = pathElements[3];

        // if there is more left of the path info then hold onto it
        if (pathElements.length == 5) {
            wreq.extraPathInfo = pathElements[4];
        }

        // Page number for a specific window of results (e.g., Atom feed or entries under a category)
        if (sreq.getParameter("page") != null) {
            try {
                wreq.pageNum = Integer.parseInt(sreq.getParameter("page"));
            } catch (NumberFormatException ignored) {
            }
        }
    }

    log.debug("handle = {}, extraPathInfo = {}, pageNum = {}", wreq.weblogHandle, wreq.extraPathInfo,
            wreq.pageNum);
}

From source file:org.nuxeo.ecm.webapp.action.LogoutAction.java

/**
 * Logs the user out. Invalidates the HTTP session so that it cannot be used
 * anymore.//  w w  w  .j ava  2s  .c  om
 *
 * @return the next page that is going to be displayed
 */
public static String logout() throws Exception {
    Map<String, String> parameters = new HashMap<String, String>();
    FacesContext context = FacesContext.getCurrentInstance();
    ExternalContext eContext = context.getExternalContext();
    Object req = eContext.getRequest();
    Object resp = eContext.getResponse();
    HttpServletRequest request = null;
    if (req instanceof HttpServletRequest) {
        request = (HttpServletRequest) req;
    }
    HttpServletResponse response = null;
    if (resp instanceof HttpServletResponse) {
        response = (HttpServletResponse) resp;
    }
    Principal principal = request.getUserPrincipal();
    NuxeoPrincipal nuxeoPrincipal = null;
    if (principal instanceof NuxeoPrincipal) {
        nuxeoPrincipal = (NuxeoPrincipal) principal;
        if (nuxeoPrincipal.isAnonymous()) {
            parameters.put(NXAuthConstants.FORCE_ANONYMOUS_LOGIN, "true");
        }
    }
    if (response != null && request != null && !context.getResponseComplete()) {
        String baseURL = BaseURL.getBaseURL(request) + NXAuthConstants.LOGOUT_PAGE;
        request.setAttribute(URLPolicyService.DISABLE_REDIRECT_REQUEST_KEY, true);
        baseURL = URIUtils.addParametersToURIQuery(baseURL, parameters);
        response.sendRedirect(baseURL);
        context.responseComplete();
    }
    return null;
}

From source file:org.nuxeo.ecm.platform.web.common.requestcontroller.filter.NuxeoRequestControllerFilter.java

public static String doFormatLogMessage(HttpServletRequest request, String info) {
    String remoteHost = RemoteHostGuessExtractor.getRemoteHost(request);
    Principal principal = request.getUserPrincipal();
    String principalName = principal != null ? principal.getName() : "none";
    String uri = request.getRequestURI();
    HttpSession session = request.getSession(false);
    String sessionId = session != null ? session.getId() : "none";
    String threadName = Thread.currentThread().getName();
    return "remote=" + remoteHost + ",principal=" + principalName + ",uri=" + uri + ",session=" + sessionId
            + ",thread=" + threadName + ",info=" + info;
}

From source file:org.apache.directory.fortress.web.control.SecUtils.java

/**
 * Enables fortress session on behalf of a java.security.Principal retrieved from the container.
 *
 * @param component/*from  w  w  w . j  a v a 2 s.com*/
 * @param servletReq
 * @param j2eePolicyMgr
 * @param accessMgr
 * @throws SecurityException
 */
public static void enableFortress(Component component, HttpServletRequest servletReq,
        J2eePolicyMgr j2eePolicyMgr, AccessMgr accessMgr) throws SecurityException {
    // Get the principal from the container:
    Principal principal = servletReq.getUserPrincipal();
    // Is this a Java EE secured page && has the User successfully authenticated already?
    boolean isSecured = principal != null;
    if (isSecured) {
        //linksLabel += " for " + principal.getName();
        if (!isLoggedIn(component)) {
            String szPrincipal = principal.toString();
            // Pull the fortress session from the realm and assert into the Web app's session along with user's perms:
            SecUtils.initializeSession(component, j2eePolicyMgr, accessMgr, szPrincipal);
        }
    }
}

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

/**
 * Returns null if user is not authenticated or authorised, otherwise returns Auth object.
 * //from  w  w w.  j  a v a  2  s.c  om
 */
public static Auth checkAuthorised(final HttpServletRequest request, HttpServletResponse response,
        ServletContext servletContext) throws IOException {

    RolePerms rolePerms = getOrCreateRolePerms(servletContext);

    Auth auth = new Auth(new Auth.Validator() {

        @Override
        public boolean isUserInRole(String role) {
            return request.isUserInRole(role);
        }

        @Override
        public boolean isAuthenticated() {
            return request.getUserPrincipal() != null;
        }
    }, rolePerms);

    switch (auth.check()) {
    case UNAUTHORISED:
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return null;
    case FORBIDDEN:
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return null;
    default:
        return auth;
    }
}

From source file:org.samlsample.control.SecUtils.java

/**
 * Enables fortress session on behalf of a java.security.Principal retrieved from the container.
 *
 * @param component//from   w w  w  .j  a v a2 s .c  o m
 * @param servletReq
 * @param j2eePolicyMgr
 * @param accessMgr
 * @throws SecurityException
 */
public static boolean enableFortress(Component component, HttpServletRequest servletReq,
        J2eePolicyMgr j2eePolicyMgr, AccessMgr accessMgr) throws SecurityException {
    boolean result = false;
    // Get the principal from the container:
    ExpiringUsernameAuthenticationToken principal = (ExpiringUsernameAuthenticationToken) servletReq
            .getUserPrincipal();
    // Is this a secured page && has the User successfully authenticated already?
    boolean isSecured = principal != null;
    if (isSecured) {
        // Only perform this step once per user web session:
        if (!isLoggedIn(component)) {
            //String userId = principal.getName();
            String userId = getUserId((SAMLCredential) principal.getCredentials());
            if (StringUtils.isEmpty(userId)) {
                // This is default where SSOCircle places email address:
                //userId = principal.getName();
                userId = getSurName((SAMLCredential) principal.getCredentials());
                if (StringUtils.isEmpty(userId)) {
                    throw new RuntimeException(
                            "No userid found in SAML assertion for principal" + principal.getName());
                }
            }
            /*
                            else
                            {
            SAMLCredential credential = (SAMLCredential)principal.getCredentials();
            for ( org.opensaml.saml2.core.Attribute attr : credential.getAttributes())
            {
                String fname = attr.getFriendlyName();
                String name = attr.getName();
                LOG.info( "saml attribute name; " + name );
                String[] attributeValues = credential.getAttributeAsStringArray(name);
                for( String val : attributeValues )
                {
                    LOG.info( "saml attribute value:" + val );
                }
            }
                            }
            */

            // Create the fortress session and assert into the Web app's session along with user's perms:
            result = SecUtils.initializeFtSession(component, j2eePolicyMgr, accessMgr, userId);
        } else {
            result = true;
        }
    } else {
        LOG.warn("Unsecured request: " + servletReq.getRequestURL());
        throw new RuntimeException("Unauthenticated user detected for request:" + servletReq.getRequestURL());
    }
    return result;
}

From source file:nl.b3p.gis.viewer.services.GisPrincipal.java

public static GisPrincipal getGisPrincipal(HttpServletRequest request, boolean flushCache) {
    HttpSession session = request.getSession();

    /* Controleren of er al een andere gebruiker is ingelogd */
    Principal user = request.getUserPrincipal();
    if (!(user instanceof GisPrincipal && request instanceof SecurityRequestWrapper)) {
        return null;
    }//from ww w  .  j  ava  2s  .c om

    String gpCode = null;
    String gpUsername = HibernateUtil.ANONYMOUS_USER;
    String gpPassword = null;

    GisPrincipal gp = (GisPrincipal) user;
    if (gp != null) {
        gpCode = gp.getCode();
        gpUsername = gp.getName();
        gpPassword = gp.getPassword();
    }

    String appCode = request.getParameter(BaseGisAction.APP_AUTH);

    Applicatie app = null;
    if (appCode != null && appCode.length() > 0) {
        app = KaartSelectieUtil.getApplicatie(appCode);
    }

    //        Boolean loginForm = (Boolean) session.getAttribute("loginForm"); // remove this
    //        if (loginForm == null) {
    //            loginForm = false;
    //        }

    /* Applicatie geen gebruikerscode en niet via formulier gekomen */
    //        if (app != null && app.getGebruikersCode() == null && !loginForm) { // this can probaly be removed
    //            session.invalidate();
    //
    //            log.debug("Applicatie zonder gebruikerscode. Terug naar login form.");
    //
    //            return null;
    //        }

    /* Gebruikerscode verschilt met huidige inlog. Automatisch inloggen. */
    if (gp != null && app != null && app.getGebruikersCode() != null
            && !app.getGebruikersCode().equals(gp.getCode())) {
        A11YResult a11yResult = (A11YResult) session.getAttribute("a11yResult");

        session.invalidate();

        gp = null;
        gpCode = app.getGebruikersCode();
        gpUsername = HibernateUtil.ANONYMOUS_USER;
        gpPassword = null;

        SecurityRequestWrapper srw = (SecurityRequestWrapper) request;

        gp = (GisPrincipal) GisSecurityRealm.authenticate(gpUsername, gpPassword, gpCode);
        srw.setUserPrincipal(gp);

        /* Fix zodat gekozen startlocatie ook werkt voor nieuwe sessie als er als andere
         * user wordt ingelogd. */
        if (a11yResult != null) {
            HttpSession newSession = request.getSession(true);
            newSession.setAttribute("a11yResult", a11yResult);
        }

        log.debug("Gebruikerscode verschilt. Automatisch ingelogd met nieuwe gebruiker.");
    }

    /* Applicatie geen gebruikerscode. Inloggen met gegevens van formulier. */
    if (app != null && app.getGebruikersCode() == null) { // check how this works
        SecurityRequestWrapper srw = (SecurityRequestWrapper) request;

        gp = (GisPrincipal) GisSecurityRealm.authenticate(gpUsername, gpPassword, gpCode);
        srw.setUserPrincipal(gp);

        log.debug("Applicatie zonder gebruikerscode. Nu ingelogd via formulier.");
    }

    return gp;
}

From source file:org.apache.roller.weblogger.ui.core.RollerSession.java

/**
 * Get RollerSession from request (and add user if not already present).
 *///  ww w .j  a v  a2 s  . c om
public static RollerSession getRollerSession(HttpServletRequest request) {
    RollerSession rollerSession = null;
    HttpSession session = request.getSession(false);
    if (session != null) {
        rollerSession = (RollerSession) session.getAttribute(ROLLER_SESSION);

        if (rollerSession == null) {
            // HttpSession with no RollerSession?
            // Must be a session that was de-serialized from a previous run.
            rollerSession = new RollerSession();
            session.setAttribute(ROLLER_SESSION, rollerSession);
        }

        Principal principal = request.getUserPrincipal();

        // If we've got a principal but no user object, then attempt to get
        // user object from user manager but *only* do this if we have been 
        // bootstrapped because under an SSO scenario we may have a 
        // principal even before we have been bootstrapped.
        if (rollerSession.getAuthenticatedUser() == null && principal != null
                && WebloggerFactory.isBootstrapped()) {
            try {

                UserManager umgr = WebloggerFactory.getWeblogger().getUserManager();
                User user = umgr.getUserByUserName(principal.getName());

                // check for OpenID username (in the form of a URL)
                if (user == null && principal.getName() != null && principal.getName().startsWith("http://")) {
                    String openidurl = principal.getName();
                    if (openidurl.endsWith("/")) {
                        openidurl = openidurl.substring(0, openidurl.length() - 1);
                    }
                    user = umgr.getUserByAttribute(UserAttribute.Attributes.OPENID_URL.toString(), openidurl);
                }

                // try one time to auto-provision, only happens if user==null
                // which means installation has SSO-enabled in security.xml
                if (user == null && WebloggerConfig.getBooleanProperty("users.sso.autoProvision.enabled")) {

                    // provisioning enabled, get provisioner and execute
                    AutoProvision provisioner = RollerContext.getAutoProvision();
                    if (provisioner != null) {
                        boolean userProvisioned = provisioner.execute(request);
                        if (userProvisioned) {
                            // try lookup again real quick
                            user = umgr.getUserByUserName(principal.getName());
                        }
                    }
                }
                // only set authenticated user if user is enabled
                if (user != null && user.getEnabled().booleanValue()) {
                    rollerSession.setAuthenticatedUser(user);
                }

            } catch (WebloggerException e) {
                log.error("ERROR: getting user object", e);
            }
        }
    }

    return rollerSession;
}