Java Code Examples for javax.servlet.http.HttpServletRequest.getUserPrincipal()

The following are Jave code examples for showing how to use getUserPrincipal() of the javax.servlet.http.HttpServletRequest class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: tomcat7   File: TestRequest.java   View Source Code Vote up 8 votes
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    req.login(USER, PWD);

    if (!req.getRemoteUser().equals(USER))
        throw new ServletException();
    if (!req.getUserPrincipal().getName().equals(USER))
        throw new ServletException();

    req.logout();

    if (req.getRemoteUser() != null)
        throw new ServletException();
    if (req.getUserPrincipal() != null)
        throw new ServletException();

    resp.getWriter().write(OK);
}
 
Example 2
Project: cas-server-4.2.1   File: PrincipalFromRequestUserPrincipalNonInteractiveCredentialsAction.java   View Source Code Vote up 7 votes
@Override
protected Credential constructCredentialsFromRequest(
        final RequestContext context) {
    final HttpServletRequest request = WebUtils
            .getHttpServletRequest(context);
    final Principal principal = request.getUserPrincipal();

    if (principal != null) {

        logger.debug("UserPrincipal [{}] found in HttpServletRequest", principal.getName());
        return new PrincipalBearingCredential(this.principalFactory.createPrincipal(principal.getName()));
    }

    logger.debug("UserPrincipal not found in HttpServletRequest.");
    return null;
}
 
Example 3
Project: springboot-shiro-cas-mybatis   File: PrincipalFromRequestUserPrincipalNonInteractiveCredentialsAction.java   View Source Code Vote up 6 votes
@Override
protected Credential constructCredentialsFromRequest(
        final RequestContext context) {
    final HttpServletRequest request = WebUtils
            .getHttpServletRequest(context);
    final Principal principal = request.getUserPrincipal();

    if (principal != null) {

        logger.debug("UserPrincipal [{}] found in HttpServletRequest", principal.getName());
        return new PrincipalBearingCredential(this.principalFactory.createPrincipal(principal.getName()));
    }

    logger.debug("UserPrincipal not found in HttpServletRequest.");
    return null;
}
 
Example 4
Project: springboot-shiro-cas-mybatis   File: PrincipalFromRequestUserPrincipalNonInteractiveCredentialsAction.java   View Source Code Vote up 6 votes
@Override
protected Credential constructCredentialsFromRequest(
        final RequestContext context) {
    final HttpServletRequest request = WebUtils
            .getHttpServletRequest(context);
    final Principal principal = request.getUserPrincipal();

    if (principal != null) {

        logger.debug("UserPrincipal [{}] found in HttpServletRequest", principal.getName());
        return new PrincipalBearingCredential(this.principalFactory.createPrincipal(principal.getName()));
    }

    logger.debug("UserPrincipal not found in HttpServletRequest.");
    return null;
}
 
Example 5
Project: jaffa-framework   File: PortletFilter.java   View Source Code Vote up 6 votes
/** On entry it is assumed that a UserSession object exists. The purpose of this
 * function is to implement any required logic to re-validate that this UserSession is
 * still ok.
 *
 * On exit, if the UserSession object still exists in the HttpSession it is assumed that
 * it has been re-validated (regardless of whether it has been updated, or re-used for
 * another user). If it has been removed from the session, the assumtion is that
 * the reAuthentication failed.
 *
 * @param request HttpRequest that holds any log in context information
 */
private void reAuthenticate(HttpServletRequest request)
        throws IOException, ServletException {
    // Get the Current Session
    UserSession us = UserSession.getUserSession(request);

    // If we have an authenticated user ...
    if (request.getUserPrincipal() != null) {
        // ...and it is the same user that the valid session is for, we are ok
        if (us.isValid() && us.getUserId().equals(request.getUserPrincipal().getName())) {
            // no nothing, life is peachy!
            return;
        } else {
            // this is a differnt user, or an invalid session, so kill this UserSession and try an auto-authenticate
            us.kill();
            autoAuthenticate(request);
            return;
        }
    }/* else {
// We have reached the security manager, with out and authenticatic user,
// but we have a user session. We must therefore just kill it and continue.
us.kill();
}*/
}
 
Example 6
Project: cas4.0.x-server-wechat   File: PrincipalFromRequestUserPrincipalNonInteractiveCredentialsAction.java   View Source Code Vote up 6 votes
@Override
protected Credential constructCredentialsFromRequest(
        final RequestContext context) {
    final HttpServletRequest request = WebUtils
            .getHttpServletRequest(context);
    final Principal principal = request.getUserPrincipal();

    if (principal != null) {

        logger.debug("UserPrincipal [{}] found in HttpServletRequest", principal.getName());
        return new PrincipalBearingCredential(new SimplePrincipal(
                principal.getName()));
    }

    logger.debug("UserPrincipal not found in HttpServletRequest.");
    return null;
}
 
Example 7
Project: apache-tomcat-7.0.73-with-comment   File: TestRequest.java   View Source Code Vote up 6 votes
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    req.login(USER, PWD);

    if (!req.getRemoteUser().equals(USER))
        throw new ServletException();
    if (!req.getUserPrincipal().getName().equals(USER))
        throw new ServletException();

    req.logout();

    if (req.getRemoteUser() != null)
        throw new ServletException();
    if (req.getUserPrincipal() != null)
        throw new ServletException();

    resp.getWriter().write(OK);
}
 
Example 8
Project: lams   File: WebUtil.java   View Source Code Vote up 6 votes
/**
    * TODO default proper exception at lams level to replace RuntimeException TODO isTesting should be removed when
    * login is done properly.
    *
    * @param req
    *            -
    * @return username from principal object
    */
   public static String getUsername(HttpServletRequest req, boolean isTesting) throws RuntimeException {
if (isTesting) {
    return "test";
}

Principal prin = req.getUserPrincipal();
if (prin == null) {
    throw new RuntimeException(
	    "Trying to get username but principal object missing. Request is " + req.toString());
}

String username = prin.getName();
if (username == null) {
    throw new RuntimeException("Name missing from principal object. Request is " + req.toString()
	    + " Principal object is " + prin.toString());
}

return username;
   }
 
Example 9
Project: hadoop   File: RMWebServices.java   View Source Code Vote up 6 votes
private UserGroupInformation getCallerUserGroupInformation(
    HttpServletRequest hsr, boolean usePrincipal) {

  String remoteUser = hsr.getRemoteUser();
  if (usePrincipal) {
    Principal princ = hsr.getUserPrincipal();
    remoteUser = princ == null ? null : princ.getName();
  }

  UserGroupInformation callerUGI = null;
  if (remoteUser != null) {
    callerUGI = UserGroupInformation.createRemoteUser(remoteUser);
  }

  return callerUGI;
}
 
Example 10
Project: seldon-core   File: AuthorizedWebMvcTagsProvider.java   View Source Code Vote up 6 votes
@Override
public Iterable<Tag> httpRequestTags(HttpServletRequest request,
           HttpServletResponse response,
           Throwable ex) {
	
	String principalName = null;
	if (request.getUserPrincipal() != null )
		principalName = request.getUserPrincipal().getName();

	return asList(WebMvcTags.method(request), WebMvcTags.uri(request), WebMvcTags.exception(ex), WebMvcTags.status(response),
			principal(principalName),
               projectName(principalName),
			deploymentName(principalName),
               deploymentVersion(principalName)
               );

	
}
 
Example 11
Project: sso   File: BindController.java   View Source Code Vote up 5 votes
/**
 * 转发绑定页面
 *
 * @param client
 * @return
 */
@RequestMapping("/bind/{client}")
public String bindPage(@PathVariable("client") String client, Model model, HttpServletRequest request) {
    Pac4jPrincipal pac4jPrincipal = (Pac4jPrincipal) request.getUserPrincipal();
    model.addAttribute("user", pac4jPrincipal.getProfile().getId());
    return "bind/" + client;
}
 
Example 12
Project: jaffa-framework   File: TagHelper.java   View Source Code Vote up 5 votes
/** A convenience method to return a hyperlink to the LabelEditor component.
 * A blank string will be returned, if the user does not have access to the component 'Jaffa.Admin.LabelEditor'.
 * @param pageContext The PageContext of the jsp.
 * @param labelFilter The label to be edited. The labelFilter should be of the type 'xyz', '[xyz]'. Values of the type 'abc [xyz] efg [zzz]' will be ignored and a blank string will be returned.
 * @return the HTML for the hyperlink to the LabelEditor component.
 */
public static String getLabelEditorLink(PageContext pageContext, String labelFilter) {
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    
    // Perform the logic only if the user has been authenticated
    if (request.getUserPrincipal() != null) {
        String labelEditorPrefix = null;
        HttpSession session = request.getSession(false);
        if (session != null) {
            // Check the session for the cached prefix
            labelEditorPrefix = (String) session.getAttribute(ATTRIBUTE_LABEL_EDITOR_LINK_PREFIX);
            if (labelEditorPrefix == null) {
                labelEditorPrefix = constructLabelEditorLinkPrefix(request);
                session.setAttribute(ATTRIBUTE_LABEL_EDITOR_LINK_PREFIX, labelEditorPrefix);
            }
        } else {
            // No session, so simply create the prefix each time
            labelEditorPrefix = constructLabelEditorLinkPrefix(request);
        }
        
        if (labelEditorPrefix.length() > 0) {
            // Ensure that the labelFilter is of the type 'xyz' or '[xyz]'
            // Remove the outer token markers, if any
            // Then proceed only if no more token-markers exist
            labelFilter = MessageHelper.removeTokenMarkers(labelFilter);
            if (!MessageHelper.hasTokens(labelFilter))
                return labelEditorPrefix + labelFilter + LABEL_EDITOR_LINK_SUFFIX;
        }
    }
    
    // We'll reach this point if the user is not aunthenticated or has no access to the component or if the labelFilter is invalid
    // Just return a blank String
    return "";
}
 
Example 13
Project: keycloak_training   File: CamelHelloProcessor.java   View Source Code Vote up 5 votes
@Override
public void process(Exchange exchange) throws Exception {
    HttpServletRequest req = exchange.getIn().getBody(HttpServletRequest.class);

    // KeycloakPrincipal encapsulates informations like token etc
    KeycloakPrincipal keycloakPrincipal = (KeycloakPrincipal) req.getUserPrincipal();

    String suffix = (String) exchange.getIn().getHeader("id");

    exchange.getOut().setHeader(Exchange.CONTENT_TYPE, "application/json");
    Message message = new Message("camel - " + suffix);
    String jsonResponse = JsonSerialization.writeValueAsString(message);
    exchange.getOut().setBody(jsonResponse);
}
 
Example 14
Project: poppynotes   File: InCommingNoteEncryptingFilter.java   View Source Code Vote up 5 votes
private HttpServletRequest encryptRequest(HttpServletRequest request) {
	ModifiableHttpServletRequest modifiableRequest = new ModifiableHttpServletRequest(request);
	Principal principal = request.getUserPrincipal();
	AuthUserResponse userDetails = userService.getUserInfoFromAuthEmail(principal.getName());
	
	try {
		InputStream encryptedNoteStream = encryptionService.encryptNote(request.getInputStream(), userDetails.getCryptKey(), principal.getName());
		modifiableRequest.setInputStream(new SimpleServletInputStream(encryptedNoteStream));
	} catch (IOException e) {
		logger.warn("Cannot fetch ServletRequest InputStream!",e);
	}
	return modifiableRequest;
}
 
Example 15
Project: sso   File: IndexController.java   View Source Code Vote up 5 votes
@GetMapping("/")
public String index(HttpServletRequest request, Model model) {
    //用户详细信息
    Principal principal = request.getUserPrincipal();
    model.addAttribute("user", principal);
    //打开index.html页面
    return "index";
}
 
Example 16
Project: parabuild-ci   File: ParabuildWebServiceServlet.java   View Source Code Vote up 5 votes
public void doPost(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws ServletException, IOException {
    final SecurityManager instance = SecurityManager.getInstance();
    final Principal userPrincipal = httpServletRequest.getUserPrincipal();
    final String name = userPrincipal.getName();
    final User userByName = instance.getUserByName(name);
//    final RightSet userRights = instance.getUserRights();
    if (!userByName.isAdmin()) httpServletResponse.sendError(401);
    super.doPost(httpServletRequest, httpServletResponse);
  }
 
Example 17
Project: keycloak_training   File: Controller.java   View Source Code Vote up 4 votes
public boolean isLoggedIn(HttpServletRequest req) {
    return req.getUserPrincipal() != null;
}
 
Example 18
Project: keycloak_training   File: Controller.java   View Source Code Vote up 4 votes
private SamlPrincipal getAccount(HttpServletRequest req) {
    SamlPrincipal principal = (SamlPrincipal)req.getUserPrincipal();
    return principal;
}
 
Example 19
Project: sso   File: UserController.java   View Source Code Vote up 4 votes
@GetMapping("/detail")
public Object detail(HttpServletRequest request) {
    //用户详细信息
    return request.getUserPrincipal();
}
 
Example 20
Project: jerrydog   File: SingleSignOn.java   View Source Code Vote up 4 votes
/**
 * Perform single-sign-on support processing for this request.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 * @param context The valve context used to invoke the next valve
 *  in the current processing pipeline
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
public void invoke(Request request, Response response,
                   ValveContext context)
    throws IOException, ServletException {

    // If this is not an HTTP request and response, just pass them on
    if (!(request instanceof HttpRequest) ||
        !(response instanceof HttpResponse)) {
        context.invokeNext(request, response);
        return;
    }
    HttpServletRequest hreq =
        (HttpServletRequest) request.getRequest();
    HttpServletResponse hres =
        (HttpServletResponse) response.getResponse();
    request.removeNote(Constants.REQ_SSOID_NOTE);

    // Has a valid user already been authenticated?
    if (debug >= 1)
        log("Process request for '" + hreq.getRequestURI() + "'");
    if (hreq.getUserPrincipal() != null) {
        if (debug >= 1)
            log(" Principal '" + hreq.getUserPrincipal().getName() +
                "' has already been authenticated");
        context.invokeNext(request, response);
        return;
    }

    // Check for the single sign on cookie
    if (debug >= 1)
        log(" Checking for SSO cookie");
    Cookie cookie = null;
    Cookie cookies[] = hreq.getCookies();
    if (cookies == null)
        cookies = new Cookie[0];
    for (int i = 0; i < cookies.length; i++) {
        if (Constants.SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) {
            cookie = cookies[i];
            break;
        }
    }
    if (cookie == null) {
        if (debug >= 1)
            log(" SSO cookie is not present");
        context.invokeNext(request, response);
        return;
    }

    // Look up the cached Principal associated with this cookie value
    if (debug >= 1)
        log(" Checking for cached principal for " + cookie.getValue());
    SingleSignOnEntry entry = lookup(cookie.getValue());
    if (entry != null) {
        if (debug >= 1)
            log(" Found cached principal '" +
                entry.principal.getName() + "' with auth type '" +
                entry.authType + "'");
        request.setNote(Constants.REQ_SSOID_NOTE, cookie.getValue());
        ((HttpRequest) request).setAuthType(entry.authType);
        ((HttpRequest) request).setUserPrincipal(entry.principal);
    } else {
        if (debug >= 1)
            log(" No cached principal found, erasing SSO cookie");
        cookie.setMaxAge(0);
        hres.addCookie(cookie);
    }

    // Invoke the next Valve in our pipeline
    context.invokeNext(request, response);

}