Java Code Examples for javax.servlet.http.HttpServletRequest#getUserPrincipal()
The following examples show how to use
javax.servlet.http.HttpServletRequest#getUserPrincipal() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebLogicRequestUpgradeStrategy.java From spring-analysis-note with MIT License | 8 votes |
@Override protected void handleSuccess(HttpServletRequest request, HttpServletResponse response, UpgradeInfo upgradeInfo, TyrusUpgradeResponse upgradeResponse) throws IOException, ServletException { response.setStatus(upgradeResponse.getStatus()); upgradeResponse.getHeaders().forEach((key, value) -> response.addHeader(key, Utils.getHeaderFromList(value))); AsyncContext asyncContext = request.startAsync(); asyncContext.setTimeout(-1L); Object nativeRequest = getNativeRequest(request); BeanWrapper beanWrapper = new BeanWrapperImpl(nativeRequest); Object httpSocket = beanWrapper.getPropertyValue("connection.connectionHandler.rawConnection"); Object webSocket = webSocketHelper.newInstance(request, httpSocket); webSocketHelper.upgrade(webSocket, httpSocket, request.getServletContext()); response.flushBuffer(); boolean isProtected = request.getUserPrincipal() != null; Writer servletWriter = servletWriterHelper.newInstance(webSocket, isProtected); Connection connection = upgradeInfo.createConnection(servletWriter, noOpCloseListener); new BeanWrapperImpl(webSocket).setPropertyValue("connection", connection); new BeanWrapperImpl(servletWriter).setPropertyValue("connection", connection); webSocketHelper.registerForReadEvent(webSocket); }
Example 2
Source File: TestServlet.java From ee8-sandbox with Apache License 2.0 | 6 votes |
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().write("This is a servlet \n"); String webName = null; if (request.getUserPrincipal() != null) { webName = request.getUserPrincipal().getName(); } response.getWriter().write("web username: " + webName + "\n"); response.getWriter().write("web user has role \"foo\": " + request.isUserInRole("foo") + "\n"); response.getWriter().write("web user has role \"bar\": " + request.isUserInRole("bar") + "\n"); response.getWriter().write("web user has role \"kaz\": " + request.isUserInRole("kaz") + "\n"); }
Example 3
Source File: ProtectedServlet.java From keycloak with Apache License 2.0 | 6 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String realm = req.getPathInfo().split("/")[1]; if (realm.contains("?")) { realm = realm.split("\\?")[0]; } if (req.getPathInfo().contains("logout")) { req.logout(); resp.sendRedirect(req.getContextPath() + "/" + realm); return; } KeycloakPrincipal principal = (KeycloakPrincipal) req.getUserPrincipal(); resp.setContentType("text/html"); PrintWriter writer = resp.getWriter(); writer.write("Realm: "); writer.write(principal.getKeycloakSecurityContext().getRealm()); writer.write("<br/>User: "); writer.write(principal.getKeycloakSecurityContext().getIdToken().getPreferredUsername()); writer.write(String.format("<br/><a href=\"/multitenant/%s/logout\">Logout</a>", realm)); }
Example 4
Source File: ApplicationFilter.java From cloud-sfsf-benefits-ext with Apache License 2.0 | 6 votes |
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String userId = null; HttpServletRequest httpRequest = (HttpServletRequest) request; try { loadECAPISession(httpRequest.getSession()); Principal userPrincipal = httpRequest.getUserPrincipal(); if (userPrincipal != null) { userId = userPrincipal.getName(); boolean isAdminUser = httpRequest.isUserInRole(ApplicationRoles.ADMINISTRATOR_ROLE); UserManager.setUserId(userId); UserManager.setIsUserAdmin(isAdminUser); // pass the request along the filter chain chain.doFilter(request, response); } } finally { UserManager.cleanUp(); storeECAPISession(httpRequest.getSession()); } }
Example 5
Source File: LoginFilterTest.java From codenvy with Eclipse Public License 1.0 | 6 votes |
@Test public void shouldWrappedPrincipalShouldNotBeTheSameAsInRequest() throws IOException, ServletException { // given HttpServletRequest request = new MockHttpServletRequest("http://localhost:8080/ws/ws", null, 0, "GET", null); when(tokenExtractor.getToken(eq(request))).thenReturn("t13f"); when(ssoServerClient.getSubject(eq("t13f"), anyString())) .thenReturn(createSubject("user@domain")); when(clientUrlExtractor.getClientUrl(eq(request))).thenReturn("http://localhost:8080/ws/ws"); SsoClientPrincipal principal = new SsoClientPrincipal("t13f", "http://localhost:8080/ws/ws", createSubject("user@domain")); request.getSession().setAttribute("principal", principal); // when filter.doFilter(request, response, chain); // then ArgumentCaptor<HttpServletRequest> captor = ArgumentCaptor.forClass(HttpServletRequest.class); verify(chain).doFilter(captor.capture(), any(ServletResponse.class)); HttpServletRequest actual = captor.getValue(); Principal actualUserPrincipal = actual.getUserPrincipal(); Assert.assertNotEquals(actualUserPrincipal, principal); }
Example 6
Source File: WebUtil.java From lams with GNU General Public License v2.0 | 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 7
Source File: SpringOAuthAuthenticationFilter.java From cxf with Apache License 2.0 | 6 votes |
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest)request; HttpServletResponse resp = (HttpServletResponse)response; List<String> authorities = (List<String>)request.getAttribute(OAUTH_AUTHORITIES); List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); if (authorities != null) { for (String authority : authorities) { grantedAuthorities.add(new SimpleGrantedAuthority(authority)); } Authentication auth = new AnonymousAuthenticationToken(UUID.randomUUID().toString(), req.getUserPrincipal(), grantedAuthorities); SecurityContextHolder.getContext().setAuthentication(auth); } chain.doFilter(req, resp); }
Example 8
Source File: PrincipalFilter.java From sinavi-jfw with Apache License 2.0 | 6 votes |
/** * {@inheritDoc} * <p> * メソッド開始時に {@link PrincipalKeeper#setPrincipal(Principal)} を、 * メソッド終了時に同メソッドに対して <code>null</code>を設定しています。 * </p> */ @Override public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest r = (HttpServletRequest) request; Principal principal = r.getUserPrincipal(); if (principal != null) { PrincipalKeeper.setPrincipal(principal); } try { chain.doFilter(request, response); } finally { PrincipalKeeper.setPrincipal(null); } }
Example 9
Source File: TestServlet.java From ee8-sandbox with Apache License 2.0 | 6 votes |
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().write("This is a servlet \n"); String webName = null; if (request.getUserPrincipal() != null) { webName = request.getUserPrincipal().getName(); } response.getWriter().write("web username: " + webName + "\n"); response.getWriter().write("web user has role \"foo\": " + request.isUserInRole("foo") + "\n"); response.getWriter().write("web user has role \"bar\": " + request.isUserInRole("bar") + "\n"); response.getWriter().write("web user has role \"kaz\": " + request.isUserInRole("kaz") + "\n"); }
Example 10
Source File: RunAsServlet.java From tomee with Apache License 2.0 | 5 votes |
public void invokeGetCallerPrincipal(final HttpServletRequest request) { // Servlet environment - running as "user" Principal principal = request.getUserPrincipal(); Assert.assertNotNull(principal); Assert.assertEquals("user", principal.getName()); // EJB environment - running as "runas" principal = secureEJBLocal.getCallerPrincipal(); Assert.assertNotNull(principal); Assert.assertEquals("runas", principal.getName()); }
Example 11
Source File: LogEventService.java From cerberus-source with GNU General Public License v3.0 | 5 votes |
@Override public void createForPublicCalls(String page, String action, String log, HttpServletRequest request) { // Only log if cerberus_log_publiccalls parameter is equal to Y. if (parameterService.getParameterBooleanByKey("cerberus_log_publiccalls", "", false)) { // The parameter cerberus_log_publiccalls is activated so we log all Public API calls. String myUser = ""; if (!(request.getUserPrincipal() == null)) { myUser = ParameterParserUtil.parseStringParam(request.getUserPrincipal().getName(), ""); } this.create(factoryLogEvent.create(0, 0, myUser, null, page, action, log, request.getRemoteAddr(), request.getLocalAddr())); } }
Example 12
Source File: AuthContext.java From onlyoffice-confluence with GNU Affero General Public License v3.0 | 5 votes |
public static boolean checkUserAuthorisation(HttpServletRequest request, HttpServletResponse response) throws IOException { Principal principal = request.getUserPrincipal(); if (principal == null) { log.error("User is not authenticated"); String fullUrl = getLoginUrl(request); response.sendRedirect(fullUrl); return false; } log.info("principal name = " + principal.getName()); return true; }
Example 13
Source File: XUserREST.java From ranger with Apache License 2.0 | 4 votes |
/** * Implements the traditional search functionalities for XUsers * * @param request * @return */ @GET @Path("/users") @Produces({ "application/xml", "application/json" }) @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_USERS + "\")") public VXUserList searchXUsers(@Context HttpServletRequest request) { String UserRoleParamName = RangerConstants.ROLE_USER; SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( request, xUserService.sortFields); String userName = null; if (request.getUserPrincipal() != null){ userName = request.getUserPrincipal().getName(); } searchUtil.extractString(request, searchCriteria, "name", "User name",null); searchUtil.extractString(request, searchCriteria, "emailAddress", "Email Address", null); searchUtil.extractInt(request, searchCriteria, "userSource", "User Source"); searchUtil.extractInt(request, searchCriteria, "isVisible", "User Visibility"); searchUtil.extractInt(request, searchCriteria, "status", "User Status"); List<String> userRolesList = searchUtil.extractStringList(request, searchCriteria, "userRoleList", "User Role List", "userRoleList", null, null); searchUtil.extractRoleString(request, searchCriteria, "userRole", "Role", null); if (CollectionUtils.isNotEmpty(userRolesList) && CollectionUtils.size(userRolesList) == 1 && userRolesList.get(0).equalsIgnoreCase(UserRoleParamName)) { if (!(searchCriteria.getParamList().containsKey("name"))) { searchCriteria.addParam("name", userName); } else if ((searchCriteria.getParamList().containsKey("name")) && userName!= null && userName.contains((String) searchCriteria.getParamList().get("name"))) { searchCriteria.addParam("name", userName); } } UserSessionBase userSession = ContextUtil.getCurrentUserSession(); if (userSession != null && userSession.getLoginId() != null) { VXUser loggedInVXUser = xUserService.getXUserByUserName(userSession .getLoginId()); if (loggedInVXUser != null) { if (loggedInVXUser.getUserRoleList().size() == 1 && loggedInVXUser.getUserRoleList().contains( RangerConstants.ROLE_USER)) { logger.info("Logged-In user having user role will be able to fetch his own user details."); if (!searchCriteria.getParamList().containsKey("name")) { searchCriteria.addParam("name", loggedInVXUser.getName()); }else if(searchCriteria.getParamList().containsKey("name") && !stringUtil.isEmpty(searchCriteria.getParamValue("name").toString()) && !searchCriteria.getParamValue("name").toString().equalsIgnoreCase(loggedInVXUser.getName())){ throw restErrorUtil.create403RESTException("Logged-In user is not allowed to access requested user data."); } } } } return xUserMgr.searchXUsers(searchCriteria); }
Example 14
Source File: ProxyUserAuthenticationFilter.java From hbase with Apache License 2.0 | 4 votes |
@Override protected void doFilter(FilterChain filterChain, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { final HttpServletRequest lowerCaseRequest = toLowerCase(request); String doAsUser = lowerCaseRequest.getParameter(DO_AS); if (doAsUser != null && !doAsUser.equals(request.getRemoteUser())) { LOG.debug("doAsUser = {}, RemoteUser = {} , RemoteAddress = {} ", doAsUser, request.getRemoteUser(), request.getRemoteAddr()); UserGroupInformation requestUgi = (request.getUserPrincipal() != null) ? UserGroupInformation.createRemoteUser(request.getRemoteUser()) : null; if (requestUgi != null) { requestUgi = UserGroupInformation.createProxyUser(doAsUser, requestUgi); try { ProxyUsers.authorize(requestUgi, request.getRemoteAddr()); final UserGroupInformation ugiF = requestUgi; request = new HttpServletRequestWrapper(request) { @Override public String getRemoteUser() { return ugiF.getShortUserName(); } @Override public Principal getUserPrincipal() { return new Principal() { @Override public String getName() { return ugiF.getUserName(); } }; } }; LOG.debug("Proxy user Authentication successful"); } catch (AuthorizationException ex) { HttpExceptionUtils.createServletExceptionResponse(response, HttpServletResponse.SC_FORBIDDEN, ex); LOG.warn("Proxy user Authentication exception", ex); return; } } } super.doFilter(filterChain, request, response); }
Example 15
Source File: FederationServlet.java From cxf-fediz with Apache License 2.0 | 4 votes |
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>WS Federation Spring Security Pre-Auth Example</title></head>"); out.println("<body>"); out.println("<h1>Hello World</h1>"); out.println("Hello world<br>"); out.println("Request url: "); out.println(request.getRequestURL()); out.println("<p>"); out.println("<br><b>User</b><p>"); Principal p = request.getUserPrincipal(); if (p != null) { out.println("Principal: " + p.getName() + "<p>"); } out.println("<br><b>Roles</b><p>"); List<String> roleListToCheck = Arrays.asList("Admin", "Manager", "User", "Authenticated"); for (String item: roleListToCheck) { out.println("Has role '" + item + "': " + ((request.isUserInRole(item)) ? "<b>yes</b>" : "no") + "<p>"); } if (p instanceof FedizPrincipal) { FedizPrincipal fp = (FedizPrincipal)p; out.println("<br><b>Claims</b><p>"); ClaimCollection claims = fp.getClaims(); for (Claim c: claims) { out.println(c.getClaimType().toString() + ": " + c.getValue() + "<p>"); } } else { out.println("Principal is not instance of FedizPrincipal"); } // Access Spring security context Authentication obj = SecurityContextHolder.getContext().getAuthentication(); System.out.println("getCredentials: " + obj.getCredentials().toString()); System.out.println("getDetails: " + obj.getDetails().toString()); System.out.println("getName: " + obj.getName().toString()); System.out.println("getAuthorities: " + obj.getAuthorities().toString()); System.out.println("getPrincipal: " + obj.getPrincipal().toString()); Element el = SecurityTokenThreadLocal.getToken(); if (el != null) { out.println("<p>Bootstrap token..."); try { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); StringWriter buffer = new StringWriter(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(el), new StreamResult(buffer)); String token = buffer.toString(); out.println("<p>" + HtmlUtils.htmlEscape(token)); } catch (Exception ex) { out.println("<p>Failed to transform cached element to string: " + ex.toString()); } } else { out.println("<p>Bootstrap token not cached in thread local storage"); } out.println("</body>"); }
Example 16
Source File: SecurityFilter.java From packagedrone with Eclipse Public License 1.0 | 4 votes |
public static boolean isLoggedIn ( final HttpServletRequest request ) { return request.getUserPrincipal () != null; }
Example 17
Source File: FederationServlet.java From cxf-fediz with Apache License 2.0 | 4 votes |
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>WS Federation Example</title></head>"); out.println("<body>"); out.println("<h1>Hello World</h1>"); out.println("Hello world<br>"); out.println("Request url: "); out.println(request.getRequestURL()); out.println("<p>"); out.println("<br><b>User</b><p>"); Principal p = request.getUserPrincipal(); if (p != null) { out.println("Principal: " + p.getName() + "<p>"); } out.println("<br><b>Roles</b><p>"); List<String> roleListToCheck = Arrays.asList("Admin", "Manager", "User", "Authenticated"); for (String item: roleListToCheck) { out.println("Has role '" + item + "': " + ((request.isUserInRole(item)) ? "<b>yes</b>" : "no") + "<p>"); } if (p instanceof FedizPrincipal) { FedizPrincipal fp = (FedizPrincipal)p; out.println("<br><b>Claims</b><p>"); ClaimCollection claims = fp.getClaims(); for (Claim c: claims) { out.println(c.getClaimType().toString() + ": " + c.getValue() + "<p>"); } } else { out.println("Principal is not instance of FedizPrincipal"); } Element el = SecurityTokenThreadLocal.getToken(); if (el != null) { out.println("<p>Bootstrap token..."); String token = null; try { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); StringWriter buffer = new StringWriter(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(el), new StreamResult(buffer)); token = buffer.toString(); out.println("<p>" + StringEscapeUtils.escapeXml11(token)); } catch (Exception ex) { out.println("<p>Failed to transform cached element to string: " + ex.toString()); } } else { out.println("<p>Bootstrap token not cached in thread local storage"); } out.println("</body>"); }
Example 18
Source File: UserIT.java From glowroot with Apache License 2.0 | 4 votes |
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) { // user principal is only captured if app actually uses it // (since it may throw exception) request.getUserPrincipal(); }
Example 19
Source File: DavServlet.java From sakai with Educational Community License v2.0 | 4 votes |
/** * Setup and cleanup around this request. * * @param req * HttpServletRequest object with the client request * @param res * HttpServletResponse object back to the client */ @SuppressWarnings("unchecked") protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, java.io.IOException { SakaidavServletInfo info = newInfo(req); // try to authenticate based on a Principal (one of ours) in the req Principal prin = req.getUserPrincipal(); if ((prin != null) && (prin instanceof DavPrincipal)) { String eid = prin.getName(); String pw = ((DavPrincipal) prin).getPassword(); Evidence e = new IdPwEvidence(eid, pw, req.getRemoteAddr()); // in older versions of this code, we didn't authenticate // if there was a session for this user. Unfortunately the // these are special non-sakai sessions, which do not // have real cookies attached. The cookie looks like // username-hostname. That means that they're easy to // fake. Since the DAV protocol doesn't actually // support sessions in the first place, most clients // won't use them. So it's a security hole without // any real benefit. Thus we check the password for // every transaction. The underlying sessions are still // a good idea, as they set the context for later // operations. But we can't depend upon the cookies for // authentication. // authenticate try { if ((eid.length() == 0) || (pw.length() == 0)) { throw new AuthenticationException("missing required fields"); } Authentication a = AuthenticationManager.authenticate(e); // No need to log in again if UsageSession is not null, active, and the eid is the // same as that resulting from the DAV basic auth authentication if ((UsageSessionService.getSession() == null || UsageSessionService.getSession().isClosed() || !a.getEid().equals(UsageSessionService.getSession().getUserEid())) && !UsageSessionService.login(a, req, UsageSessionService.EVENT_LOGIN_DAV)) { // login failed res.addHeader("WWW-Authenticate","Basic realm=\"DAV\""); res.sendError(401); return; } } catch (AuthenticationException ex) { // not authenticated res.addHeader("WWW-Authenticate","Basic realm=\"DAV\""); res.sendError(401); return; } } else { // user name missing, so can't authenticate res.addHeader("WWW-Authenticate","Basic realm=\"DAV\""); res.sendError(401); return; } // Set the client cookie if enabled as this is not done by the RequestFilter for dav requests. // This is not required by DAV clients but may be helpful in some load-balancing // configurations for session affinity across app servers. However, some Windows DAV clients // share cookies with IE7 which can lead to confusing results in the browser session. if (useCookies) { req.setAttribute(RequestFilter.ATTR_SET_COOKIE, true); } // Setup... ? try { doDispatch(info, req, res); } finally { log(req, info); } }
Example 20
Source File: DavServlet.java From sakai with Educational Community License v2.0 | 4 votes |
/** * Setup and cleanup around this request. * * @param req * HttpServletRequest object with the client request * @param res * HttpServletResponse object back to the client */ @SuppressWarnings("unchecked") protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, java.io.IOException { SakaidavServletInfo info = newInfo(req); // try to authenticate based on a Principal (one of ours) in the req Principal prin = req.getUserPrincipal(); if ((prin != null) && (prin instanceof DavPrincipal)) { String eid = prin.getName(); String pw = ((DavPrincipal) prin).getPassword(); Evidence e = new IdPwEvidence(eid, pw, req.getRemoteAddr()); // in older versions of this code, we didn't authenticate // if there was a session for this user. Unfortunately the // these are special non-sakai sessions, which do not // have real cookies attached. The cookie looks like // username-hostname. That means that they're easy to // fake. Since the DAV protocol doesn't actually // support sessions in the first place, most clients // won't use them. So it's a security hole without // any real benefit. Thus we check the password for // every transaction. The underlying sessions are still // a good idea, as they set the context for later // operations. But we can't depend upon the cookies for // authentication. // authenticate try { if ((eid.length() == 0) || (pw.length() == 0)) { throw new AuthenticationException("missing required fields"); } Authentication a = AuthenticationManager.authenticate(e); // No need to log in again if UsageSession is not null, active, and the eid is the // same as that resulting from the DAV basic auth authentication if ((UsageSessionService.getSession() == null || UsageSessionService.getSession().isClosed() || !a.getEid().equals(UsageSessionService.getSession().getUserEid())) && !UsageSessionService.login(a, req, UsageSessionService.EVENT_LOGIN_DAV)) { // login failed res.addHeader("WWW-Authenticate","Basic realm=\"DAV\""); res.sendError(401); return; } } catch (AuthenticationException ex) { // not authenticated res.addHeader("WWW-Authenticate","Basic realm=\"DAV\""); res.sendError(401); return; } } else { // user name missing, so can't authenticate res.addHeader("WWW-Authenticate","Basic realm=\"DAV\""); res.sendError(401); return; } // Set the client cookie if enabled as this is not done by the RequestFilter for dav requests. // This is not required by DAV clients but may be helpful in some load-balancing // configurations for session affinity across app servers. However, some Windows DAV clients // share cookies with IE7 which can lead to confusing results in the browser session. if (useCookies) { req.setAttribute(RequestFilter.ATTR_SET_COOKIE, true); } // Setup... ? try { doDispatch(info, req, res); } finally { log(req, info); } }