List of usage examples for javax.servlet.http HttpServletRequest getUserPrincipal
public java.security.Principal getUserPrincipal();
java.security.Principal
object containing the name of the current authenticated user. From source file:org.gss_project.gss.server.rest.Webdav.java
@Override public void service(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { String method = request.getMethod(); if (logger.isDebugEnabled()) { String path = request.getPathInfo(); if (path == null) path = request.getServletPath(); if (path == null || path.equals("")) path = "/"; logger.debug("[" + method + "] " + path); }/*w ww . j a v a 2 s . c o m*/ try { User user = null; if (request.getUserPrincipal() != null) { // Let unauthenticated // OPTIONS go through; // all others will be // blocked by // authentication anyway // before we get here. user = getService().findUser(request.getUserPrincipal().getName()); if (user == null) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } request.setAttribute(USER_ATTRIBUTE, user); request.setAttribute(OWNER_ATTRIBUTE, user); } catch (RpcException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } if (method.equals(METHOD_GET)) doGet(request, response); else if (method.equals(METHOD_POST)) doPost(request, response); else if (method.equals(METHOD_PUT)) doPut(request, response); else if (method.equals(METHOD_DELETE)) doDelete(request, response); else if (method.equals(METHOD_HEAD)) doHead(request, response); else if (method.equals(METHOD_PROPFIND)) doPropfind(request, response); else if (method.equals(METHOD_PROPPATCH)) doProppatch(request, response); else if (method.equals(METHOD_MKCOL)) doMkcol(request, response); else if (method.equals(METHOD_COPY)) doCopy(request, response); else if (method.equals(METHOD_MOVE)) doMove(request, response); else if (method.equals(METHOD_LOCK)) doLock(request, response); else if (method.equals(METHOD_UNLOCK)) doUnlock(request, response); else if (method.equals(METHOD_OPTIONS)) doOptions(request, response); else // DefaultServlet processing for TRACE, etc. super.service(request, response); }
From source file:org.motrice.bpm.hippo.util.ServletUserNameUtil.java
public static UserInfo getUserName(final HttpServletRequest request) { UserInfo result = null;/* w w w . j a v a 2 s . co m*/ /* * log.error("ServletUserNameUtil:error"); * log.warn("ServletUserNameUtil:warn"); * log.info("ServletUserNameUtil:info"); * log.debug("ServletUserNameUtil:debug"); * log.trace("ServletUserNameUtil:trace"); */ checkEngine(); // / trying shibboleth String Shib_Identity_Provider = (String) request.getAttribute("Shib-Identity-Provider"); log.info("request.getAttribute(Shib-Identity-Provider) = " + Shib_Identity_Provider); String Shib_Application_ID = (String) request.getAttribute("Shib-Application-ID"); log.info("request.getAttribute(Shib-Application-ID) = " + Shib_Application_ID); // log.info("request.getHeader(Shib-Identity-Provider) = " // + request.getHeader("Shib-Identity-Provider")); if ((Shib_Identity_Provider != null) && (Shib_Application_ID.equals("default"))) { // the names of the attributes are set in attribute-*.xml files in // /etc/shibboleth for the SP // Different IdPs might privide different attributes, it probable // makes sence // to make the mapping in the attribute-*.xml to the same attribute name for the different IdPs. String Subject_SerialNumber = (String) request.getAttribute("Subject_SerialNumber"); // String gn = (String) request.getAttribute("GivenName"); String gn = getAttributeShibboleth("GivenName", request); String sn = getAttributeShibboleth("Subject_Surname", request); //String sn_id = (String) request.getAttribute("sn_id"); String sn_id = null; String cn = getAttributeShibboleth("Subject_CommonName", request); log.info("Subject_SerialNumber = " + Subject_SerialNumber + " gn = " + gn + " sn = " + sn + " cn = " + cn); result = engine.getUserBySerial(Subject_SerialNumber, gn, sn, sn_id, cn); } if ((Shib_Identity_Provider != null) && (Shib_Application_ID.equals("internal"))) { // the names of the attributes are set in attribute-*.xml files in // /etc/shibboleth for the SP // Different IdPs might privide different attributes, it probable // makes sence // to make the mapping in the attribute-*.xml to the same attribute name for the different IdPs. String cn = getAttributeShibboleth("Subject_CommonName", request); log.info(" cn = " + cn); String userBaseDn = ConfigUtil.getConfigProperties().getProperty("userDirectoryService.userBaseDn"); String baseDn = ConfigUtil.getConfigProperties().getProperty("userDirectoryService.baseDn"); // String dn ="cn="+cn+",ou=Personal,ou=Organisation,ou=Malmo,dc=adm,dc=malmo,dc=se" ; // NOTE String dn = "cn=" + cn + "," + userBaseDn + "," + baseDn; // log.info(" dn = " + dn); // log.info("Subject_SerialNumber = " + Subject_SerialNumber + " gn = " // + gn + " sn = " + sn + " cn = " + cn); result = engine.getUserByDn(dn); } if (result == null) { log.info("Trying openAM"); // OPEN AM String dn = request.getHeader("x-ipl-dn"); String ser = request.getHeader("x-ipl-ser"); String certificateSubject = request.getHeader("x-ipl-cer-sub"); if (dn == null) { if (ser != null) { result = engine.getUserBySerial(ser, certificateSubject); } } else { if (ser == null) { result = engine.getUserByDn(dn); } else { log.debug("Only one of header x-ipl-dn and x-ipl-ser should be used"); log.debug("x-ipl-dn=[ {} ]", dn); log.debug("x-ipl-ser=[ {} ]", ser); /** * TODO workaround to detect by path komin/extern */ String pathInfo = request.getPathInfo(); if (pathInfo != null && pathInfo.indexOf("komin") > 0) { result = engine.getUserByDn(dn); } else { result = engine.getUserBySerial(ser, certificateSubject); } } } if (result == null) { log.info("userName header not found, get user principal instead"); log.info("Only one of header x-ipl-dn and x-ipl-ser should be used"); log.info("x-ipl-dn=[{} ]", dn); log.info("x-ipl-ser=[{} ]", ser); log.info("x-ipl-cer-sub=[{}]", certificateSubject); Principal principal = request.getUserPrincipal(); if (principal != null) { String hippoDn = "CN=" + principal.getName() + ",OU=Personal,OU=Organisation,OU=Hippo Internal User,DC=adm,DC=inherit,DC=se"; result = engine.getUserByDn(hippoDn); // "CN=tesetj,OU=Personal,OU=Organisation,OU=Malmo,DC=adm,DC=malmo,DC=se" } } log.info("Render page with userInfo=[ {} ]", result); Enumeration attributes = request.getAttributeNames(); while (attributes.hasMoreElements()) { String attr_name = (String) attributes.nextElement(); Object attr_val = request.getAttribute(attr_name); log.info(attr_name + " = " + attr_val); } } log.info("request.getAttribute(GivenName) = {} ", getAttributeShibboleth("GivenName", request)); log.info("request.getAttribute(sn_id) = {} ", getAttributeShibboleth("sn_id", request)); log.info("request.getAttribute(SecurityLevelDescription) = {} ", getAttributeShibboleth("SecurityLevelDescription", request)); log.info("request.getAttribute(Subject_CountryName) = {} ", getAttributeShibboleth("Subject_CountryName", request)); log.info("request.getAttribute(Subject_CommonName) = {} ", getAttributeShibboleth("Subject_CommonName", request)); log.info("request.getAttribute(CertificateSerialNumber) = {} ", getAttributeShibboleth("CertificateSerialNumber", request)); log.info("request.getAttribute(dateOfBirth) = {} ", getAttributeShibboleth("dateOfBirth", request)); log.info("request.getAttribute(Subject_OrganisationName) = {} ", getAttributeShibboleth("Subject_OrganisationName", request)); log.info("request.getAttribute(Issuer_OrganizationName) = {} ", getAttributeShibboleth("Issuer_OrganizationName", request)); log.info("request.getAttribute(sn_type) = {} ", getAttributeShibboleth("sn_type", request)); log.info("request.getAttribute(Subject_Surname) = {} ", getAttributeShibboleth("Subject_Surname", request)); log.info("request.getAttribute(Subject_SerialNumber) = {} ", getAttributeShibboleth("Subject_SerialNumber", request)); log.info("request.getAttribute(Gender) = ", getAttributeShibboleth("Gender", request)); log.info("request.getAttribute(ValidationOcspResponse, request) = {} ", getAttributeShibboleth("ValidationOcspResponse", request)); log.info("request.getAttribute(SecurityLevel) = {} ", getAttributeShibboleth("SecurityLevel", request)); log.info("request.getAttribute(Issuer_CommonName) = {} ", getAttributeShibboleth("Issuer_CommonName", request)); log.info("request.getAttribute(age) = {} ", getAttributeShibboleth("age", request)); log.info("request.getAttribute(affiliation) = {} ", getAttributeShibboleth("affiliation", request)); log.info("request.getAttribute(entitlement) = {} ", getAttributeShibboleth("entitlement", request)); log.info("request.getAttribute(eppn) = {} ", getAttributeShibboleth("eppn", request)); log.info("request.getAttribute(persistent-id) = {} ", getAttributeShibboleth("persistent-id", request)); log.info("request.getAttribute(telephoneNumber) = {} ", getAttributeShibboleth("telephoneNumber", request)); log.info("request.getAttribute(unscoped-affiliation) = {} ", getAttributeShibboleth("unscoped-affiliation", request)); return result; }
From source file:org.sakaiproject.dav.DavServlet.java
/** * Setup and cleanup around this request. * /*from w ww . j a v a 2 s .c o m*/ * @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(); //SAK-14776 - In order for WAS to return the Principal with getUserPrincipal() //security needs to be enabled. We have employed a custom JAAS module to handle //WAS's user security for the Sakai WebApp. SakaiWASLoginModule also acts as a wrapper //to fetch PrivateCredentials from WAS. The user password is stored in those //credentials. Once all information is obtained, the Principal is remade and //DavServlet is none the wiser. //The Login Module code can be found at: //https://source.sakaiproject.org/contrib/websphere/was-login-module/ /* removed 2013-09-10 -AZ if ("websphere".equals(ServerConfigurationService.getString("servlet.container"))) { //Fetch the credentials collection from the Subject. //A wrapper is used here because we need access to //com.ibm.ws.security.auth.WSLoginHelperImpl Iterator credItr = null; try { credItr = SakaiWASLoginModule.getSubject().getPrivateCredentials().iterator(); } catch (Exception e) { M_log.error("SAKAIDAV: Unabled to obtain WAS credentials.", e); } String pw = ""; while (credItr != null && credItr.hasNext()) { //look for the Key-Value pair Object cred = credItr.next(); if( cred instanceof SakaiWASLoginModule.SakaiWASLoginKeyValue ) { SakaiWASLoginModule.SakaiWASLoginKeyValue entry = (SakaiWASLoginModule.SakaiWASLoginKeyValue)cred; //extract the password from the Key-Value pair if( "sakai.dav.pw".equals(entry.getKey()) ) { pw = (String)entry.getValue(); String eid = prin.getName(); //remake the Principal with the user eid //and the recently fetched password prin = new DavPrincipal(eid,pw); break; } } } } */ if ((prin != null) && (prin instanceof DavPrincipal)) { String eid = prin.getName(); String pw = ((DavPrincipal) prin).getPassword(); Evidence e = new IdPwEvidence(eid, pw); // 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); } }
From source file:jeeves.server.sources.http.JeevesServlet.java
private void execute(HttpServletRequest req, HttpServletResponse res) throws IOException { String ip = req.getRemoteAddr(); // if we do have the optional x-forwarded-for request header then // use whatever is in it to record ip address of client String forwardedFor = req.getHeader("x-forwarded-for"); if (forwardedFor != null) ip = forwardedFor;/* w ww . ja v a 2 s .co m*/ Log.info(Log.REQUEST, "=========================================================="); Log.info(Log.REQUEST, "HTML Request (from " + ip + ") : " + req.getRequestURI()); if (Log.isDebugEnabled(Log.REQUEST)) { Log.debug(Log.REQUEST, "Method : " + req.getMethod()); Log.debug(Log.REQUEST, "Content type : " + req.getContentType()); // Log.debug(Log.REQUEST, "Context path : "+ req.getContextPath()); // Log.debug(Log.REQUEST, "Char encoding: "+ req.getCharacterEncoding()); Log.debug(Log.REQUEST, "Accept : " + req.getHeader("Accept")); // Log.debug(Log.REQUEST, "Server name : "+ req.getServerName()); // Log.debug(Log.REQUEST, "Server port : "+ req.getServerPort()); } // for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) { // String theHeader = (String)e.nextElement(); // if(Log.isDebugEnabled(Log.REQUEST)) { // Log.debug(Log.REQUEST, "Got header: "+theHeader); // Log.debug(Log.REQUEST, "With value: "+req.getHeader(theHeader)); // } // } HttpSession httpSession = req.getSession(); if (Log.isDebugEnabled(Log.REQUEST)) Log.debug(Log.REQUEST, "Session id is " + httpSession.getId()); UserSession session = (UserSession) httpSession.getAttribute("session"); //------------------------------------------------------------------------ //--- create a new session if doesn't exist if (session == null) { //--- create session session = new UserSession(); httpSession.setAttribute("session", session); if (Log.isDebugEnabled(Log.REQUEST)) Log.debug(Log.REQUEST, "Session created for client : " + ip); } session.setProperty("realSession", httpSession); //------------------------------------------------------------------------ //--- build service request ServiceRequest srvReq = null; //--- create request try { srvReq = ServiceRequestFactory.create(req, res, jeeves.getUploadDir(), jeeves.getMaxUploadSize()); } catch (FileUploadTooBigEx e) { StringBuffer sb = new StringBuffer(); sb.append("Opgeladen bestand overschrijdt de maximaal toegelaten grootte van " + jeeves.getMaxUploadSize() + " Mb\n"); sb.append("Error : " + e.getClass().getName() + "\n"); res.sendError(400, sb.toString()); // now stick the stack trace on the end and log the whole lot sb.append("Stack :\n"); sb.append(Util.getStackTrace(e)); Log.error(Log.REQUEST, sb.toString()); return; } catch (FileTypeNotAllowedEx e) { StringBuffer sb = new StringBuffer(); sb.append("Bestand heeft niet het juiste type\n"); sb.append("Error : " + e.getClass().getName() + "\n"); res.sendError(400, sb.toString()); // now stick the stack trace on the end and log the whole lot sb.append("Stack :\n"); sb.append(Util.getStackTrace(e)); Log.error(Log.REQUEST, sb.toString()); return; } catch (Exception e) { StringBuffer sb = new StringBuffer(); sb.append("Cannot build ServiceRequest\n"); sb.append("Cause : " + e.getMessage() + "\n"); sb.append("Error : " + e.getClass().getName() + "\n"); res.sendError(400, sb.toString()); // now stick the stack trace on the end and log the whole lot sb.append("Stack :\n"); sb.append(Util.getStackTrace(e)); Log.error(Log.REQUEST, sb.toString()); return; } if ("user.agiv.login".equals(srvReq.getService())) { if (srvReq.getParams() != null && srvReq.getParams().getChild("wa") != null && srvReq.getParams().getChild("wa").getTextTrim().equals("wsignoutcleanup1.0")) { srvReq.setService("user.agiv.logout"); } else { Principal p = req.getUserPrincipal(); if (p != null && p instanceof FederationPrincipal/* && SecurityTokenThreadLocal.getToken()==null*/) { FederationPrincipal fp = (FederationPrincipal) p; /* for (Claim c: fp.getClaims()) { System.out.println(c.getClaimType().toString() + ":" + (c.getValue()!=null ? c.getValue().toString() : "")); } */ Map<String, String> roleProfileMapping = new HashMap<String, String>(); String profile = null; roleProfileMapping.put("Authenticated", "RegisteredUser"); roleProfileMapping.put(nodeType + " Metadata Admin", "Administrator"); roleProfileMapping.put(nodeType + " Metadata Editor", "Editor"); roleProfileMapping.put(nodeType + " Metadata Hoofdeditor", "Hoofdeditor"); List<String> roleListToCheck = Arrays.asList(nodeType + " Metadata Admin", nodeType + " Metadata Hoofdeditor", nodeType + " Metadata Editor", "Authenticated"); for (String item : roleListToCheck) { if (req.isUserInRole(item)) { profile = roleProfileMapping.get(item); break; } } String contactid = Util.getClaimValue(fp, "contactid"); session.authenticate(contactid, contactid/* + "_" + Util.getClaimValue(fp,"name")*/, Util.getClaimValue(fp, "givenname"), Util.getClaimValue(fp, "surname"), profile != null ? profile : "RegisteredUser", Util.getClaimValue(fp, "emailaddress")); List<Map<String, String>> groups = new ArrayList<Map<String, String>>(); Map<String, String> group = new HashMap<String, String>(); String parentorganisationid = Util.getClaimValue(fp, "parentorganisationid"); String parentorganisationdisplayname = Util.getClaimValue(fp, "parentorganisationdisplayname"); group.put("name", StringUtils.isBlank(parentorganisationid) ? Util.getClaimValue(fp, "organisationid") : parentorganisationid); group.put("description", StringUtils.isBlank(parentorganisationdisplayname) ? (StringUtils.isBlank(parentorganisationid) ? Util.getClaimValue(fp, "organisationdisplayname") : parentorganisationid) : parentorganisationdisplayname); groups.add(group); session.setProperty("groups", groups); } else { System.out.println("Principal is not instance of FederationPrincipal"); } } } //--- execute request jeeves.dispatch(srvReq, session); }
From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.FormAuthenticator.java
/** Perform form authentication. * Called from SecurityHandler./*from www .j a v a 2 s . c om*/ * @return UserPrincipal if authenticated else null. */ public Principal authenticate(UserRealm realm, String pathInContext, HttpRequest httpRequest, HttpResponse httpResponse) throws IOException { HttpServletRequest request = (ServletHttpRequest) httpRequest.getWrapper(); HttpServletResponse response = httpResponse == null ? null : (HttpServletResponse) httpResponse.getWrapper(); // Handle paths String uri = pathInContext; // Setup session HttpSession session = request.getSession(response != null); if (session == null) return null; // Handle a request for authentication. if (uri.substring(uri.lastIndexOf("/") + 1).startsWith(__J_SECURITY_CHECK)) { // Check the session object for login info. FormCredential form_cred = new FormCredential(); form_cred.authenticate(realm, request.getParameter(__J_USERNAME), request.getParameter(__J_PASSWORD), httpRequest); String nuri = (String) session.getAttribute(__J_URI); if (nuri == null || nuri.length() == 0) { nuri = request.getContextPath(); if (nuri.length() == 0) nuri = "/"; } if (form_cred._userPrincipal != null) { // Authenticated OK if (log.isDebugEnabled()) log.debug("Form authentication OK for " + form_cred._jUserName); session.removeAttribute(__J_URI); // Remove popped return URI. httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH); httpRequest.setAuthUser(form_cred._jUserName); httpRequest.setUserPrincipal(form_cred._userPrincipal); session.setAttribute(__J_AUTHENTICATED, form_cred); // Sign-on to SSO mechanism if (realm instanceof SSORealm) { ((SSORealm) realm).setSingleSignOn(httpRequest, httpResponse, form_cred._userPrincipal, new Password(form_cred._jPassword)); } // Redirect to original request if (response != null) { response.setContentLength(0); response.sendRedirect(response.encodeRedirectURL(nuri)); } } else if (response != null) { if (log.isDebugEnabled()) log.debug("Form authentication FAILED for " + form_cred._jUserName); if (_formErrorPage != null) { response.setContentLength(0); response.sendRedirect( response.encodeRedirectURL(URI.addPaths(request.getContextPath(), _formErrorPage))); } else { response.sendError(HttpResponse.__403_Forbidden); } } // Security check is always false, only true after final redirection. return null; } // Check if the session is already authenticated. FormCredential form_cred = (FormCredential) session.getAttribute(__J_AUTHENTICATED); if (form_cred != null) { // We have a form credential. Has it been distributed? if (form_cred._userPrincipal == null) { // This form_cred appears to have been distributed. Need to reauth form_cred.authenticate(realm, httpRequest); // Sign-on to SSO mechanism if (form_cred._userPrincipal != null && realm instanceof SSORealm) { ((SSORealm) realm).setSingleSignOn(httpRequest, httpResponse, form_cred._userPrincipal, new Password(form_cred._jPassword)); } } else if (!realm.reauthenticate(form_cred._userPrincipal)) // Else check that it is still authenticated. form_cred._userPrincipal = null; // If this credential is still authenticated if (form_cred._userPrincipal != null) { if (log.isDebugEnabled()) log.debug("FORM Authenticated for " + form_cred._userPrincipal.getName()); httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH); httpRequest.setAuthUser(form_cred._userPrincipal.getName()); httpRequest.setUserPrincipal(form_cred._userPrincipal); return form_cred._userPrincipal; } else session.setAttribute(__J_AUTHENTICATED, null); } else if (realm instanceof SSORealm) { // Try a single sign on. Credential cred = ((SSORealm) realm).getSingleSignOn(httpRequest, httpResponse); if (httpRequest.hasUserPrincipal()) { form_cred = new FormCredential(); form_cred._userPrincipal = request.getUserPrincipal(); form_cred._jUserName = form_cred._userPrincipal.getName(); if (cred != null) form_cred._jPassword = cred.toString(); if (log.isDebugEnabled()) log.debug("SSO for " + form_cred._userPrincipal); httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH); session.setAttribute(__J_AUTHENTICATED, form_cred); return form_cred._userPrincipal; } } // Don't authenticate authform or errorpage if (isLoginOrErrorPage(pathInContext)) return SecurityConstraint.__NOBODY; // redirect to login page if (response != null) { if (httpRequest.getQuery() != null) uri += "?" + httpRequest.getQuery(); session.setAttribute(__J_URI, request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + URI.addPaths(request.getContextPath(), uri)); response.setContentLength(0); response.sendRedirect( response.encodeRedirectURL(URI.addPaths(request.getContextPath(), _formLoginPage))); } return null; }
From source file:org.apache.catalina.servlets.DefaultServlet.java
/** * Show HTTP header information./*w ww. ja v a 2s . c om*/ * * @param req Description of the Parameter */ protected void showRequestInfo(HttpServletRequest req) { System.out.println(); System.out.println("SlideDAV Request Info"); System.out.println(); // Show generic info System.out.println("Encoding : " + req.getCharacterEncoding()); System.out.println("Length : " + req.getContentLength()); System.out.println("Type : " + req.getContentType()); System.out.println(); System.out.println("Parameters"); Enumeration parameters = req.getParameterNames(); while (parameters.hasMoreElements()) { String paramName = (String) parameters.nextElement(); String[] values = req.getParameterValues(paramName); System.out.print(paramName + " : "); for (int i = 0; i < values.length; i++) { System.out.print(values[i] + ", "); } System.out.println(); } System.out.println(); System.out.println("Protocol : " + req.getProtocol()); System.out.println("Address : " + req.getRemoteAddr()); System.out.println("Host : " + req.getRemoteHost()); System.out.println("Scheme : " + req.getScheme()); System.out.println("Server Name : " + req.getServerName()); System.out.println("Server Port : " + req.getServerPort()); System.out.println(); System.out.println("Attributes"); Enumeration attributes = req.getAttributeNames(); while (attributes.hasMoreElements()) { String attributeName = (String) attributes.nextElement(); System.out.print(attributeName + " : "); System.out.println(req.getAttribute(attributeName).toString()); } System.out.println(); // Show HTTP info System.out.println(); System.out.println("HTTP Header Info"); System.out.println(); System.out.println("Authentication Type : " + req.getAuthType()); System.out.println("HTTP Method : " + req.getMethod()); System.out.println("Path Info : " + req.getPathInfo()); System.out.println("Path translated : " + req.getPathTranslated()); System.out.println("Query string : " + req.getQueryString()); System.out.println("Remote user : " + req.getRemoteUser()); System.out.println("Requested session id : " + req.getRequestedSessionId()); System.out.println("Request URI : " + req.getRequestURI()); System.out.println("Context path : " + req.getContextPath()); System.out.println("Servlet path : " + req.getServletPath()); System.out.println("User principal : " + req.getUserPrincipal()); System.out.println(); System.out.println("Headers : "); Enumeration headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String headerName = (String) headers.nextElement(); System.out.print(headerName + " : "); System.out.println(req.getHeader(headerName)); } System.out.println(); System.out.println(); }
From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java
private Set<String> getUserRoles(HttpServletRequest req) { LOGGER.info("========Getting the user roles========="); Set<String> userGroups = null; Set<String> allGroups = userConnectivityService.getAllGroups(); if (null == allGroups || allGroups.isEmpty()) { LOGGER.error("No groups fetched from Authenticated User.....All groups is empty.Returning null"); } else {/* w ww. ja v a2 s. c o m*/ userGroups = new HashSet<String>(); for (String group : allGroups) { if (null != group && !group.isEmpty() && req.isUserInRole(group)) { LOGGER.info("Added group is: " + group); userGroups.add(group); } } LOGGER.info("List of fetched user roles:"); for (String userRole : userGroups) { LOGGER.info(userRole + ","); } if (userGroups.isEmpty()) { String userName = WebServiceUtil.EMPTY_STRING; if (req.getUserPrincipal() != null) { userName = req.getUserPrincipal().getName(); } LOGGER.error("No roles found in Authenticated User for " + userName); userGroups = null; } } return userGroups; }
From source file:com.ephesoft.dcma.webservice.util.WebServiceHelper.java
/** * Gets the user roles.//www. j a v a 2 s.c om * * @param req the req * @return the user roles */ public Set<String> getUserRoles(final HttpServletRequest req) { LOGGER.info("========Getting the user roles========="); Set<String> allGroups = userConnectivityService.getAllGroups(); if (null == allGroups || allGroups.isEmpty()) { LOGGER.error("No groups fetched from Authenticated User.....All groups is empty.Returning null"); return null; } Set<String> userGroups = new HashSet<String>(); for (String group : allGroups) { if (null != group && !group.isEmpty()) { if (req.isUserInRole(group)) { LOGGER.info("Added group is: " + group); userGroups.add(group); } } } LOGGER.info("List of fetched user roles:"); for (String userRole : userGroups) { LOGGER.info(userRole + ","); } if (userGroups.isEmpty()) { String userName = WebServiceUtil.EMPTY_STRING; if (req.getUserPrincipal() != null) { userName = req.getUserPrincipal().getName(); } LOGGER.error("No roles found in Authenticated User for " + userName); userGroups = null; } return userGroups; }
From source file:org.infoglue.cms.security.InfoGlueAuthenticationFilter.java
/** * This filter is basically what secures Infoglue and enforces the authentication framework. *///from w ww . j a va2 s .com public void doFilter(ServletRequest request, ServletResponse response, FilterChain fc) throws ServletException, IOException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; try { if (CmsPropertyHandler.getServletContext() == null) { CmsPropertyHandler.setServletContext(httpServletRequest.getContextPath()); } String URI = httpServletRequest.getRequestURI(); String URL = httpServletRequest.getRequestURL().toString(); if (logger.isInfoEnabled()) { logger.info("URI: + " + URI); logger.info("URL: + " + URL); } String requestURI = URLDecoder.decode(getContextRelativeURI(httpServletRequest), "UTF-8"); if (URI == null) logger.error("URI was null - requestURI:" + requestURI); if (URL == null) logger.error("URL was null - requestURI:" + requestURI); if (requestURI == null) logger.error("requestURI was null"); if (loginUrl == null) { logger.error("loginUrl was null - fix this."); loginUrl = "Login.action"; } if (invalidLoginUrl == null) { logger.error("invalidLoginUrl was null - fix this."); invalidLoginUrl = "Login!invalidLogin.action"; } if (logoutUrl == null) { logger.error("logoutUrl was null - fix this."); logoutUrl = "ExtranetLogin!logout.action"; } if (uriMatcher == null) { logger.error("uriMatcher was null - fix this."); String filterURIs = filterConfig.getInitParameter(FILTER_URIS_PARAMETER); uriMatcher = URIMatcher.compilePatterns(splitString(filterURIs, ","), false); } if (!CmsPropertyHandler.getIsValidSetup() && (URI.indexOf("Install") == -1 && URI.indexOf(".action") > -1)) { httpServletResponse.sendRedirect("Install!input.action"); return; } //Here are the url:s/paths that must be skipped by the security framework for it to work. Login screens etc must be reachable naturally. if (URI != null && URL != null && (URI.indexOf(loginUrl) > -1 || URL.indexOf(loginUrl) > -1 || URI.indexOf("Login.action") > -1 || URL.indexOf("Login.action") > -1 || URI.indexOf(invalidLoginUrl) > -1 || URL.indexOf(invalidLoginUrl) > -1 || URI.indexOf("Login!invalidLogin.action") > -1 || URL.indexOf("Login!invalidLogin.action") > -1 || URI.indexOf(logoutUrl) > -1 || URI.indexOf("Login!logout.action") > -1 || URL.indexOf(logoutUrl) > -1 || URI.indexOf("UpdateCache") > -1 || URI.indexOf("protectedRedirect.jsp") > -1 || uriMatcher.matches(requestURI))) { fc.doFilter(request, response); return; } // make sure we've got an HTTP request if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) throw new ServletException("InfoGlue Filter protects only HTTP resources"); HttpSession session = ((HttpServletRequest) request).getSession(); String sessionTimeout = CmsPropertyHandler.getSessionTimeout(); try { Integer.parseInt(sessionTimeout); } catch (Exception e) { sessionTimeout = "1800"; } if (sessionTimeout == null) sessionTimeout = "1800"; session.setMaxInactiveInterval(new Integer(sessionTimeout).intValue()); // if our attribute's already present, don't do anything //logger.info("User:" + session.getAttribute(INFOGLUE_FILTER_USER)); if (session != null && session.getAttribute(INFOGLUE_FILTER_USER) != null) { //logger.info("Found user in session:" + session.getAttribute(INFOGLUE_FILTER_USER)); //if(successLoginBaseUrl != null && !URL.startsWith(successLoginBaseUrl)) //{ // checkSuccessRedirect(request, response, URL); //} //else //{ fc.doFilter(request, response); return; //} } // otherwise, we need to authenticate somehow boolean isAdministrator = false; String userName = request.getParameter("j_username"); String password = request.getParameter("j_password"); if (userName != null && password != null) { String administratorUserName = CmsPropertyHandler.getAdministratorUserName(); boolean matchesRootPassword = CmsPropertyHandler.getMatchesAdministratorPassword(password); isAdministrator = (userName.equalsIgnoreCase(administratorUserName) && matchesRootPassword) ? true : false; } //First we check if the user is logged in to the container context if (!isAdministrator) { logger.info("Principal:" + httpServletRequest.getUserPrincipal()); if (httpServletRequest.getUserPrincipal() != null && !(httpServletRequest.getUserPrincipal() instanceof InfoGluePrincipal)) { userName = httpServletRequest.getUserPrincipal().getName(); logger.info("Now trusting the container logged in identity..."); } } String authenticatedUserName = userName; if (!isAdministrator) { String encodedUserNameCookie = httpHelper.getCookie(httpServletRequest, "iguserid"); logger.info("encodedUserNameCookie:" + encodedUserNameCookie); if (encodedUserNameCookie != null && !encodedUserNameCookie.equals("")) { byte[] bytes = Base64.decodeBase64(encodedUserNameCookie); encodedUserNameCookie = new String(bytes, "utf-8"); //encodedUserNameCookie = encodedUserNameCookie.replaceAll("IGEQ", "="); logger.info("encodedUserNameCookie:" + encodedUserNameCookie); String servletContextUserName = (String) filterConfig.getServletContext() .getAttribute(encodedUserNameCookie); logger.info("servletContextUserName:" + servletContextUserName); if (servletContextUserName != null && !servletContextUserName.equals("")) { authenticatedUserName = servletContextUserName; } else { Cookie cookie_iguserid = new Cookie("iguserid", "none"); cookie_iguserid.setPath("/"); cookie_iguserid.setMaxAge(0); httpServletResponse.addCookie(cookie_iguserid); Cookie cookie_igpassword = new Cookie("igpassword", "none"); cookie_igpassword.setPath("/"); cookie_igpassword.setMaxAge(0); httpServletResponse.addCookie(cookie_igpassword); authenticatedUserName = authenticateUser(httpServletRequest, httpServletResponse, fc); } } else { authenticatedUserName = authenticateUser(httpServletRequest, httpServletResponse, fc); } } logger.info("authenticatedUserName:" + authenticatedUserName); if (authenticatedUserName != null) { logger.info("Getting the principal from user name:" + authenticatedUserName); InfoGluePrincipal user = getAuthenticatedUser(authenticatedUserName); if (user == null || (!user.getIsAdministrator() && !hasAuthorizedRole(user))) { //throw new Exception("This user is not authorized to log in..."); httpServletResponse.sendRedirect("unauthorizedLogin.jsp"); NotificationMessage notificationMessage = new NotificationMessage("Authorization failed:", "Authorization", authenticatedUserName, NotificationMessage.AUTHORIZATION_FAILED, "" + authenticatedUserName, "name"); TransactionHistoryController.getController().create(notificationMessage); return; } //TODO - we must fix so these caches are individual to the person - now a login will slow down for all //CacheController.clearCache("authorizationCache"); //CacheController.clearCache("personalAuthorizationCache", user.getName()); CacheController.clearCacheForGroup("personalAuthorizationCache", user.getName()); // Store the authenticated user in the session if (session != null) { session.setAttribute(INFOGLUE_FILTER_USER, user); setUserProperties(session, user); } //TEST - transferring auth to deliverworking try { if (userName != null && password != null) { DesEncryptionHelper encHelper = new DesEncryptionHelper(); String encryptedName = encHelper.encrypt(userName); String encryptedPassword = encHelper.encrypt(password); String encryptedNameAsBase64 = Base64 .encodeBase64URLSafeString(encryptedName.getBytes("utf-8")); String encryptedPasswordAsBase64 = Base64 .encodeBase64URLSafeString(encryptedPassword.getBytes("utf-8")); String deliverBaseUrl = CmsPropertyHandler.getComponentRendererUrl(); String[] parts = deliverBaseUrl.split("/"); deliverBaseUrl = "/" + parts[parts.length - 1]; //logger.info("used cmsBaseUrl:" + cmsBaseUrl); ServletContext servletContext = filterConfig.getServletContext().getContext(deliverBaseUrl); if (servletContext == null) { logger.error("Could not autologin to " + deliverBaseUrl + ". Set cross context = true in Tomcat config."); } else { logger.info("Added encryptedName:" + encryptedName + " = " + user.getName() + " to deliver context"); servletContext.setAttribute(encryptedName, user.getName()); } int cmsCookieTimeout = 1800; //30 minutes default String cmsCookieTimeoutString = null; //CmsPropertyHandler.getCmsCookieTimeout(); if (cmsCookieTimeoutString != null) { try { cmsCookieTimeout = Integer.parseInt(cmsCookieTimeoutString.trim()); } catch (Exception e) { } } //Cookie cookie_iguserid = new Cookie("iguserid", encryptedName.replaceAll("=", "IGEQ")); Cookie cookie_iguserid = new Cookie("iguserid", encryptedNameAsBase64); cookie_iguserid.setPath("/"); cookie_iguserid.setMaxAge(cmsCookieTimeout); httpServletResponse.addCookie(cookie_iguserid); //Cookie cookie_igpassword = new Cookie ("igpassword", encryptedPassword.replaceAll("=", "IGEQ")); Cookie cookie_igpassword = new Cookie("igpassword", encryptedPasswordAsBase64); cookie_igpassword.setPath("/"); cookie_igpassword.setMaxAge(cmsCookieTimeout); httpServletResponse.addCookie(cookie_igpassword); //logger.info(encryptedName + "=" + userName); //logger.info("After attribute:" + servletContext.getAttribute(encryptedName)); } } catch (Exception e) { logger.error("Error: " + e.getMessage(), e); } //END TEST String logUserName = userName; if (logUserName == null || logUserName.equals("") && user != null) logUserName = user.getName(); if (logUserName == null || logUserName.equals("")) logUserName = authenticatedUserName; if (logUserName == null || logUserName.equals("")) logUserName = "Unknown"; NotificationMessage notificationMessage = new NotificationMessage("Login success:", "Authentication", logUserName, NotificationMessage.AUTHENTICATION_SUCCESS, "" + authenticatedUserName, "name"); TransactionHistoryController.getController().create(notificationMessage); if (successLoginBaseUrl != null && !URL.startsWith(successLoginBaseUrl)) { checkSuccessRedirect(request, response, URL); } else { fc.doFilter(request, response); return; } } else { if (userName != null && !userName.equals("")) { NotificationMessage notificationMessage = new NotificationMessage("Login failed:", "Authentication", userName, NotificationMessage.AUTHENTICATION_FAILED, "" + userName, "name"); TransactionHistoryController.getController().create(notificationMessage); } } } catch (Exception e) { logger.error("Error authenticating user:" + e.getMessage(), e); httpServletRequest.setAttribute("error", new Exception( "Error in authentication filter - look at the server error log (usually catalina.out) for reason but the most common one is problem connecting to the database or a faulty connection user or limited access for that account.")); httpServletResponse.sendError(500); return; } }
From source file:org.apache.nifi.processors.standard.HandleHttpRequest.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { try {//from w w w .j a v a 2s . c o m if (!initialized.get()) { initializeServer(context); } } catch (Exception e) { context.yield(); throw new ProcessException("Failed to initialize the server", e); } final HttpRequestContainer container = containerQueue.poll(); if (container == null) { return; } final long start = System.nanoTime(); final HttpServletRequest request = container.getRequest(); FlowFile flowFile = session.create(); try { flowFile = session.importFrom(request.getInputStream(), flowFile); } catch (final IOException e) { getLogger().error("Failed to receive content from HTTP Request from {} due to {}", new Object[] { request.getRemoteAddr(), e }); session.remove(flowFile); return; } final String charset = request.getCharacterEncoding() == null ? context.getProperty(URL_CHARACTER_SET).getValue() : request.getCharacterEncoding(); final String contextIdentifier = UUID.randomUUID().toString(); final Map<String, String> attributes = new HashMap<>(); try { putAttribute(attributes, HTTPUtils.HTTP_CONTEXT_ID, contextIdentifier); putAttribute(attributes, "mime.type", request.getContentType()); putAttribute(attributes, "http.servlet.path", request.getServletPath()); putAttribute(attributes, "http.context.path", request.getContextPath()); putAttribute(attributes, "http.method", request.getMethod()); putAttribute(attributes, "http.local.addr", request.getLocalAddr()); putAttribute(attributes, HTTPUtils.HTTP_LOCAL_NAME, request.getLocalName()); final String queryString = request.getQueryString(); if (queryString != null) { putAttribute(attributes, "http.query.string", URLDecoder.decode(queryString, charset)); } putAttribute(attributes, HTTPUtils.HTTP_REMOTE_HOST, request.getRemoteHost()); putAttribute(attributes, "http.remote.addr", request.getRemoteAddr()); putAttribute(attributes, "http.remote.user", request.getRemoteUser()); putAttribute(attributes, HTTPUtils.HTTP_REQUEST_URI, request.getRequestURI()); putAttribute(attributes, "http.request.url", request.getRequestURL().toString()); putAttribute(attributes, "http.auth.type", request.getAuthType()); putAttribute(attributes, "http.requested.session.id", request.getRequestedSessionId()); final DispatcherType dispatcherType = request.getDispatcherType(); if (dispatcherType != null) { putAttribute(attributes, "http.dispatcher.type", dispatcherType.name()); } putAttribute(attributes, "http.character.encoding", request.getCharacterEncoding()); putAttribute(attributes, "http.locale", request.getLocale()); putAttribute(attributes, "http.server.name", request.getServerName()); putAttribute(attributes, HTTPUtils.HTTP_PORT, request.getServerPort()); final Enumeration<String> paramEnumeration = request.getParameterNames(); while (paramEnumeration.hasMoreElements()) { final String paramName = paramEnumeration.nextElement(); final String value = request.getParameter(paramName); attributes.put("http.param." + paramName, value); } final Cookie[] cookies = request.getCookies(); if (cookies != null) { for (final Cookie cookie : cookies) { final String name = cookie.getName(); final String cookiePrefix = "http.cookie." + name + "."; attributes.put(cookiePrefix + "value", cookie.getValue()); attributes.put(cookiePrefix + "domain", cookie.getDomain()); attributes.put(cookiePrefix + "path", cookie.getPath()); attributes.put(cookiePrefix + "max.age", String.valueOf(cookie.getMaxAge())); attributes.put(cookiePrefix + "version", String.valueOf(cookie.getVersion())); attributes.put(cookiePrefix + "secure", String.valueOf(cookie.getSecure())); } } if (queryString != null) { final String[] params = URL_QUERY_PARAM_DELIMITER.split(queryString); for (final String keyValueString : params) { final int indexOf = keyValueString.indexOf("="); if (indexOf < 0) { // no =, then it's just a key with no value attributes.put("http.query.param." + URLDecoder.decode(keyValueString, charset), ""); } else { final String key = keyValueString.substring(0, indexOf); final String value; if (indexOf == keyValueString.length() - 1) { value = ""; } else { value = keyValueString.substring(indexOf + 1); } attributes.put("http.query.param." + URLDecoder.decode(key, charset), URLDecoder.decode(value, charset)); } } } } catch (final UnsupportedEncodingException uee) { throw new ProcessException("Invalid character encoding", uee); // won't happen because charset has been validated } final Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); final String headerValue = request.getHeader(headerName); putAttribute(attributes, "http.headers." + headerName, headerValue); } final Principal principal = request.getUserPrincipal(); if (principal != null) { putAttribute(attributes, "http.principal.name", principal.getName()); } final X509Certificate certs[] = (X509Certificate[]) request .getAttribute("javax.servlet.request.X509Certificate"); final String subjectDn; if (certs != null && certs.length > 0) { final X509Certificate cert = certs[0]; subjectDn = cert.getSubjectDN().getName(); final String issuerDn = cert.getIssuerDN().getName(); putAttribute(attributes, HTTPUtils.HTTP_SSL_CERT, subjectDn); putAttribute(attributes, "http.issuer.dn", issuerDn); } else { subjectDn = null; } flowFile = session.putAllAttributes(flowFile, attributes); final HttpContextMap contextMap = context.getProperty(HTTP_CONTEXT_MAP) .asControllerService(HttpContextMap.class); final boolean registered = contextMap.register(contextIdentifier, request, container.getResponse(), container.getContext()); if (!registered) { getLogger().warn( "Received request from {} but could not process it because too many requests are already outstanding; responding with SERVICE_UNAVAILABLE", new Object[] { request.getRemoteAddr() }); try { container.getResponse().setStatus(Status.SERVICE_UNAVAILABLE.getStatusCode()); container.getResponse().flushBuffer(); container.getContext().complete(); } catch (final Exception e) { getLogger().warn("Failed to respond with SERVICE_UNAVAILABLE message to {} due to {}", new Object[] { request.getRemoteAddr(), e }); } session.remove(flowFile); return; } final long receiveMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); session.getProvenanceReporter().receive(flowFile, HTTPUtils.getURI(attributes), "Received from " + request.getRemoteAddr() + (subjectDn == null ? "" : " with DN=" + subjectDn), receiveMillis); session.transfer(flowFile, REL_SUCCESS); getLogger().info("Transferring {} to 'success'; received from {}", new Object[] { flowFile, request.getRemoteAddr() }); }