List of usage examples for javax.servlet.http HttpServletRequest getAuthType
public String getAuthType();
From source file:MyServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>"); out.println("User Authentication"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("<H1>User Authentication</H1>"); String type = request.getAuthType(); out.println("Welcome to this secure page.<BR>"); out.println("Authentication mechanism: " + type + "<BR>"); Principal principal = request.getUserPrincipal(); out.println("Your username is: " + principal.getName() + "<BR>"); out.println("</BODY>"); out.println("</HTML>"); }
From source file:AuthenticationSnoop.java
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<HTML><BODY>"); out.println("<H1>This is a password protected resource</H1>"); out.println("<PRE>"); out.println("User Name: " + req.getRemoteUser()); String name = (req.getUserPrincipal() == null) ? null : req.getUserPrincipal().getName(); out.println("Principal Name: " + name); out.println("Authentication Type: " + req.getAuthType()); out.println("Is a Manager: " + req.isUserInRole("manager")); out.println("</PRE>"); out.println("</BODY></HTML>"); }
From source file:com.ibm.xsp.webdav.DAVCredentials.java
/** * Updates a new or existing Credential with the user's authentication * information/* ww w. ja v a2 s . c o m*/ * * @param req * Servlet Request with credential header information */ public void updateCredentials(HttpServletRequest req) { // We retrieve username from the session and check // if we have a password from basic authentication // in the header. LTPATokens are retrieved from the // session or request header Session s = null; String authType = req.getAuthType(); // Web Authentication type; LOGGER.debug("Authentication type: " + authType); // First the cookies this.updateLTPAfromRequest(req); try { s = DominoProxy.getUserSession(); // NotesSession // TODO: Figure out if we can use s.getCredentials(); this.userName = s.getUserName(); this.updateLTPAfromSession(s, req); } catch (NotesException e) { LOGGER.error("Failed to retrieve username from NotesSession:" + e.getMessage(), e); } // Get data from the basic authorization - might overwrite the // username String authHeader = req.getHeader("Authorization"); if (authHeader == null) { // There is no authentication information LOGGER.trace("No Authorization header for new user information found, User:" + this.userName); } else { String decLog = authHeader.substring(authType.length() + 1); BASE64Decoder d = new BASE64Decoder(); try { String result = new String(d.decodeBuffer(decLog)); // Now we have a String username:password if (result.indexOf(":") < 0) { // Something went wrong, we don't have a : in the string LOGGER.error("Maleformed username/password: " + result); } else { // Store it String usrpwd[] = result.split(":"); // The username in the basic authentication might be used in // other // places so we keep that one for the moment this.userName = usrpwd[0].trim().equals("") ? this.userName : usrpwd[0]; this.passWord = usrpwd[1]; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } LOGGER.debug(this.toString()); }
From source file:com.icesoft.faces.webapp.http.servlet.ServletEnvironmentRequest.java
public ServletEnvironmentRequest(Object request, HttpSession session, Authorization authorization) { HttpServletRequest initialRequest = (HttpServletRequest) request; this.session = session; this.authorization = authorization; //Copy common data authType = initialRequest.getAuthType(); contextPath = initialRequest.getContextPath(); remoteUser = initialRequest.getRemoteUser(); userPrincipal = initialRequest.getUserPrincipal(); requestedSessionId = initialRequest.getRequestedSessionId(); requestedSessionIdValid = initialRequest.isRequestedSessionIdValid(); attributes = new HashMap(); Enumeration attributeNames = initialRequest.getAttributeNames(); while (attributeNames.hasMoreElements()) { String name = (String) attributeNames.nextElement(); Object attribute = initialRequest.getAttribute(name); if ((null != name) && (null != attribute)) { attributes.put(name, attribute); }/* www . j a va 2s .co m*/ } // Warning: For some reason, the various javax.include.* attributes are // not available via the getAttributeNames() call. This may be limited // to a Liferay issue but when the MainPortlet dispatches the call to // the MainServlet, all of the javax.include.* attributes can be // retrieved using this.request.getAttribute() but they do NOT appear in // the Enumeration of names returned by getAttributeNames(). So here // we manually add them to our map to ensure we can find them later. String[] incAttrKeys = Constants.INC_CONSTANTS; for (int index = 0; index < incAttrKeys.length; index++) { String incAttrKey = incAttrKeys[index]; Object incAttrVal = initialRequest.getAttribute(incAttrKey); if (incAttrVal != null) { attributes.put(incAttrKey, initialRequest.getAttribute(incAttrKey)); } } headers = new HashMap(); Enumeration headerNames = initialRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = (String) headerNames.nextElement(); Enumeration values = initialRequest.getHeaders(name); headers.put(name, Collections.list(values)); } parameters = new HashMap(); Enumeration parameterNames = initialRequest.getParameterNames(); while (parameterNames.hasMoreElements()) { String name = (String) parameterNames.nextElement(); parameters.put(name, initialRequest.getParameterValues(name)); } scheme = initialRequest.getScheme(); serverName = initialRequest.getServerName(); serverPort = initialRequest.getServerPort(); secure = initialRequest.isSecure(); //Copy servlet specific data cookies = initialRequest.getCookies(); method = initialRequest.getMethod(); pathInfo = initialRequest.getPathInfo(); pathTranslated = initialRequest.getPathTranslated(); queryString = initialRequest.getQueryString(); requestURI = initialRequest.getRequestURI(); try { requestURL = initialRequest.getRequestURL(); } catch (NullPointerException e) { //TODO remove this catch block when GlassFish bug is addressed if (log.isErrorEnabled()) { log.error("Null Protocol Scheme in request", e); } HttpServletRequest req = initialRequest; requestURL = new StringBuffer( "http://" + req.getServerName() + ":" + req.getServerPort() + req.getRequestURI()); } servletPath = initialRequest.getServletPath(); servletSession = initialRequest.getSession(); isRequestedSessionIdFromCookie = initialRequest.isRequestedSessionIdFromCookie(); isRequestedSessionIdFromURL = initialRequest.isRequestedSessionIdFromURL(); characterEncoding = initialRequest.getCharacterEncoding(); contentLength = initialRequest.getContentLength(); contentType = initialRequest.getContentType(); protocol = initialRequest.getProtocol(); remoteAddr = initialRequest.getRemoteAddr(); remoteHost = initialRequest.getRemoteHost(); initializeServlet2point4Properties(initialRequest); }
From source file:se.vgregion.portal.requestlogger.RequestLoggerController.java
private Map<String, String> getRequestInfo(PortletRequest request) { Map<String, String> requestResult = new TreeMap<String, String>(); HttpServletRequest httpRequest = PortalUtil.getHttpServletRequest(request); requestResult.put("RemoteUser", httpRequest.getRemoteUser()); requestResult.put("P3P.USER_LOGIN_ID", getRemoteUserId(request)); requestResult.put("RemoteAddr", httpRequest.getRemoteAddr()); requestResult.put("RemoteHost", httpRequest.getRemoteHost()); requestResult.put("RemotePort", String.valueOf(httpRequest.getRemotePort())); requestResult.put("AuthType", httpRequest.getAuthType()); requestResult.put("CharacterEncoding", httpRequest.getCharacterEncoding()); requestResult.put("ContentLength", String.valueOf(httpRequest.getContentLength())); requestResult.put("ContentType", httpRequest.getContentType()); requestResult.put("ContextPath", httpRequest.getContextPath()); requestResult.put("LocalAddr", httpRequest.getLocalAddr()); requestResult.put("Locale", httpRequest.getLocale().toString()); requestResult.put("LocalName", httpRequest.getLocalName()); requestResult.put("LocalPort", String.valueOf(httpRequest.getLocalPort())); requestResult.put("Method", httpRequest.getMethod()); requestResult.put("PathInfo", httpRequest.getPathInfo()); requestResult.put("PathTranslated", httpRequest.getPathTranslated()); requestResult.put("Protocol", httpRequest.getProtocol()); requestResult.put("QueryString", httpRequest.getQueryString()); requestResult.put("RequestedSessionId", httpRequest.getRequestedSessionId()); requestResult.put("RequestURI", httpRequest.getRequestURI()); requestResult.put("Scheme", httpRequest.getScheme()); requestResult.put("ServerName", httpRequest.getServerName()); requestResult.put("ServerPort", String.valueOf(httpRequest.getServerPort())); requestResult.put("ServletPath", httpRequest.getServletPath()); return requestResult; }
From source file:com.vmware.identity.samlservice.impl.AuthnRequestStateTLSClientAuthenticationFilter.java
@Override public void authenticate(AuthnRequestState t) throws SamlServiceException { log.debug("AuthnRequestStateTLSClientAuthenticationFilter.authenticate is called"); Validate.notNull(t);/*from w w w.ja v a2s . c om*/ IdmAccessor accessor = t.getIdmAccessor(); Validate.notNull(accessor); HttpServletRequest request = t.getRequest(); Validate.notNull(request); AuthnRequest authnRequest = t.getAuthnRequest(); Validate.notNull(authnRequest); PrincipalId principalId = null; X509Certificate certChain[] = null; //Get from the custom header first. String certStr = request.getHeader(AuthnRequestStateTLSClientAuthenticationFilter.clientCertHeader); if (certStr != null && certStr.length() > 0 && request.getAuthType() == SecurityRequestWrapper.VMWARE_CLIENT_CERT_AUTH) { ByteArrayInputStream bais = null; CertificateFactory cf; try { cf = CertificateFactory.getInstance("X.509"); bais = new ByteArrayInputStream(Base64.decode(certStr)); X509Certificate cert = (X509Certificate) cf.generateCertificate(bais); certChain = new X509Certificate[] { cert }; } catch (CertificateException e1) { log.error("Error reading client certificate from http header. ", e1); ValidationResult vr = new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED, WebSSOError.UNAUTHORIZED, WebSSOError.INVALID_CREDENTIAL); t.setValidationResult(vr); throw new SamlServiceException("Client Certificate error.", e1); } } // Get from standard place of sl client cert location if (certChain == null || certChain.length == 0) { certChain = (X509Certificate[]) request .getAttribute(AuthnRequestStateTLSClientAuthenticationFilter.clientCertAttributeName); } if (certChain == null || certChain.length == 0) { ValidationResult vr = new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED, WebSSOError.UNAUTHORIZED, WebSSOError.NO_CLIENT_CERT); t.setValidationResult(vr); } else { try { principalId = accessor.authenticate(certChain); Validate.notNull(principalId, "principalId"); } catch (Exception ex) { // could not authenticate with the certificate ValidationResult vr = new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED, WebSSOError.UNAUTHORIZED, WebSSOError.INVALID_CREDENTIAL); t.setValidationResult(vr); } } if (principalId != null) { t.setPrincipalId(principalId); t.setAuthnMethod(AuthnMethod.TLSCLIENT); } }
From source file:PrintCGI.java
/** * Prints CGI Environment Variables in a table * /*from w ww . j av a2 s . c o m*/ * @param request * @param response * @throws IOException */ public void printCGIValues(HttpServletRequest request, HttpServletResponse response) throws IOException { String headers = null; String htmlHeader = "<HTML><HEAD><TITLE> CGI Environment Variables </TITLE></HEAD><BODY>"; String htmlFooter = "</BODY></HTML>"; response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(htmlHeader); out.println("<TABLE ALIGN=CENTER BORDER=1>"); out.println("<tr><th> CGI Variable </th><th> Value </th>"); out.println("<tr><td align=center>Authentication Type</td>"); out.println("<td align=center>" + request.getAuthType() + "</td></tr>"); out.println("<tr><td align=center>Content Type</td>"); out.println("<td align=center>" + request.getContentType() + "</td></tr>"); out.println("<tr><td align=center>Content Type Length</td>"); out.println("<td align=center>" + request.getContentLength() + "</td></tr>"); out.println("<tr><td align=center>Query String</td>"); out.println("<td align=center>" + request.getMethod() + "</td></tr>"); out.println("<tr><td align=center>IP Address</td>"); out.println("<td align=center>" + request.getRemoteAddr() + "</td></tr>"); out.println("<tr><td align=center>Host Name</td>"); out.println("<td align=center>" + request.getRemoteHost() + "</td></tr>"); out.println("<tr><td align=center>Request URL</td>"); out.println("<td align=center>" + request.getRequestURI() + "</td></tr>"); out.println("<tr><td align=center>Servlet Path</td>"); out.println("<td align=center>" + request.getServletPath() + "</td></tr>"); out.println("<tr><td align=center>Server's Name</td>"); out.println("<td align=center>" + request.getServerName() + "</td></tr>"); out.println("<tr><td align=center>Server's Port</td>"); out.println("<td align=center>" + request.getServerPort() + "</td></tr>"); out.println("</TABLE><BR>"); out.println(htmlFooter); }
From source file:org.jasig.cas.client.authentication.AuthenticationFilter.java
public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException { final HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; final HttpSession session = request.getSession(false); final Assertion assertion = session != null ? (Assertion) session.getAttribute(CONST_CAS_ASSERTION) : null; logger.debug(this.getClass() + ".doFilter() request.getAuthType() = " + request.getAuthType()); response = new DebugResponseWrapper(response); if (assertion != null) { filterChain.doFilter(request, response); return;// ww w.j a v a 2s . c o m } final String serviceUrl = constructServiceUrl(request, response); final String ticket = CommonUtils.safeGetParameter(request, getArtifactParameterName()); final boolean wasGatewayed = this.gatewayStorage.hasGatewayedAlready(request, serviceUrl); if (CommonUtils.isNotBlank(ticket) || wasGatewayed) { filterChain.doFilter(request, response); return; } final String modifiedServiceUrl; logger.debug("no ticket and no assertion found"); if (this.gateway) { logger.debug("setting gateway attribute in session"); modifiedServiceUrl = this.gatewayStorage.storeGatewayInformation(request, serviceUrl); } else { modifiedServiceUrl = serviceUrl; } if (logger.isDebugEnabled()) { logger.debug("Constructed service url: " + modifiedServiceUrl); } final String urlToRedirectTo = CommonUtils.constructRedirectUrl(this.casServerLoginUrl, getServiceParameterName(), modifiedServiceUrl, this.renew, this.gateway); if (logger.isDebugEnabled()) { logger.debug("redirecting to \"" + urlToRedirectTo + "\""); } response.sendRedirect(urlToRedirectTo); }
From source file:gateway.auth.PiazzaBasicAuthenticationEntryPoint.java
@Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx) throws IOException, ServletException { response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\""); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); // Create a Response Object ErrorResponse error = new ErrorResponse("Gateway is unable to authenticate the provided user.", "Gateway"); try {/* ww w .jav a2 s. c o m*/ // Log the request logger.log( String.format("Unable to authenticate a user with Auth Type %s and Header %s", request.getAuthType(), request.getHeader("Authorization").toString()), PiazzaLogger.ERROR); } catch (Exception exception) { String errorString = String.format("Exception encountered during Authorization check: %s.", exception.getMessage()); LOGGER.error(errorString, exception); logger.log(errorString, PiazzaLogger.ERROR); } // Write back the response writer.println(new ObjectMapper().writeValueAsString(error)); }
From source file:org.gluu.oxtrust.action.Authenticator.java
/** * Authenticate using credentials passed from web request header *//* w ww. j a v a 2s. co m*/ public boolean shibboleth2Authenticate() { log.debug("Checking if user authenticated with shibboleth already"); boolean result = false; HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext() .getRequest(); String authType = request.getAuthType(); String userUid = request.getHeader("REMOTE_USER"); String userUidlower = request.getHeader("remote_user"); Enumeration<?> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = (String) headerNames.nextElement(); log.trace(headerName + "-->" + request.getHeader(headerName)); } log.debug("Username is " + userUid); log.debug("UsernameLower is " + userUidlower); log.debug("AuthType is " + authType); Map<String, String[]> headers = FacesContext.getCurrentInstance().getExternalContext() .getRequestHeaderValuesMap(); for (String name : headers.keySet()) { log.trace(name + "==>" + StringUtils.join(headers.get(name))); } if (StringHelper.isEmpty(userUid) || StringHelper.isEmpty(authType) || !authType.equals("shibboleth")) { result = false; return result; } Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+"); Matcher matcher = pattern.matcher(userUid); User user = null; if (matcher.matches()) { // Find user by uid user = personService.getPersonByEmail(userUid); } else { // Find user by uid user = personService.getUserByUid(userUid); } if (user == null) { result = false; return result; } log.debug("Person Inum is " + user.getInum()); if (GluuStatus.ACTIVE.getValue().equals(user.getAttribute("gluuStatus"))) { credentials.setUsername(user.getUid()); // credentials.setPassword(""); Principal principal = new SimplePrincipal(user.getUid()); log.debug("Principal is " + principal.toString()); identity.acceptExternallyAuthenticatedPrincipal(principal); log.info("User '{0}' authenticated with shibboleth already", userUid); identity.quietLogin(); postLogin(user); Contexts.getSessionContext().set(OxTrustConstants.APPLICATION_AUTHORIZATION_TYPE, OxTrustConstants.APPLICATION_AUTHORIZATION_NAME_SHIBBOLETH2); result = true; if (Events.exists()) { facesMessages.clear(); Events.instance().raiseEvent(Identity.EVENT_LOGIN_SUCCESSFUL); } } else { result = false; } return result; }