use of javax.servlet.http.HttpServletRequestWrapper in project azure-tools-for-java by Microsoft.
the class LogoutServlet method service.
@Override
public void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
try {
final Configuration configuration = configurationCache.load();
final ApplicationSettings applicationSettings = applicationSettingsLoader.load();
// the finishLogout parameter set
if (request.getParameter("finishLogout") == null) {
String tokenString = null;
final Cookie[] cookies = request.getCookies();
for (final Cookie cookie : cookies) {
if (cookie.getName().equals("id_token")) {
tokenString = cookie.getValue();
break;
}
}
final String redirectURL = String.format("%s%spost_logout_redirect_uri=%s%s%s", configuration.getLogoutEndPoint(), configuration.getLogoutEndPoint().getName().contains("?") ? "&" : "?", URLEncoder.encode(applicationSettings.getRedirectURL().getValue(), "UTF-8"), URLEncoder.encode(request.getRequestURI(), "UTF-8"), URLEncoder.encode("?finishLogout=true", "UTF-8"));
response.setHeader("Authorization", String.format("Bearer %s", tokenString));
response.sendRedirect(redirectURL);
return;
}
// setup clearing the cookies and invalidate the session
for (final Cookie cookie : request.getCookies()) {
if (cookie.getName().equals("id_token")) {
cookie.setMaxAge(0);
response.addCookie(cookie);
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
}
if (cookie.getName().equals("JSESSIONID") || cookie.getName().equals("SESSON")) {
cookie.setMaxAge(0);
response.addCookie(cookie);
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
}
}
final HttpServletRequest newRequest = new HttpServletRequestWrapper(request) {
@Override
public Cookie[] getCookies() {
final List<Cookie> cookieList = new ArrayList<Cookie>();
for (Cookie cookie : request.getCookies()) {
if (!cookie.getName().equals("SESSION") && !cookie.getName().equals("JSESSIONID")) {
cookieList.add(cookie);
}
}
final Cookie[] cookieArray = new Cookie[cookieList.size()];
cookieList.toArray(cookieArray);
return cookieArray;
}
};
// Second stage. Forward the request so the cookies are cleared
if (request.getAttribute("logout") == null) {
request.setAttribute("logout", Boolean.TRUE);
request.getRequestDispatcher(request.getRequestURI() + "?finishLogout=true").forward(newRequest, response);
return;
}
// Final stage. Return to the application landing page
response.sendRedirect(applicationSettings.getRedirectURL().getValue());
return;
} catch (IOException | GeneralException | PreconditionException e) {
LOGGER.warn(e.getMessage(), e);
final ApplicationSettings applicationSettings = applicationSettingsLoader.load();
response.sendRedirect(applicationSettings.getRedirectURL().getValue());
}
}
use of javax.servlet.http.HttpServletRequestWrapper in project ORCID-Source by ORCID.
the class AcceptFilter method doFilterInternal.
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String accept = request.getHeader("accept");
String path = ((HttpServletRequest) request).getRequestURI();
String contentType = request.getHeader("Content-Type");
if (accept == null || accept.equals("*/*")) {
HttpServletRequestWrapper requestWrapper = null;
if (isValidAcceptType(contentType))
requestWrapper = new AcceptHeaderRequestWrapper(request, contentType);
else if (OrcidUrlManager.getPathWithoutContextPath(request).startsWith("/oauth/"))
requestWrapper = new AcceptHeaderRequestWrapper(request, MediaType.APPLICATION_JSON);
else
requestWrapper = new AcceptHeaderRequestWrapper(request, VND_ORCID_XML);
filterChain.doFilter(requestWrapper, response);
} else {
filterChain.doFilter(request, response);
}
}
use of javax.servlet.http.HttpServletRequestWrapper in project opennms by OpenNMS.
the class OriginHeaderFilter method doFilter.
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
if (request instanceof HttpServletRequest) {
final HttpServletRequest req = (HttpServletRequest) request;
final String header = req.getHeader("Origin");
if (header != null && header.startsWith("file://")) {
/*
* file://* is technically an invalid Origin: for CORS, but it appears Cordova
* sometimes sends it so we need to filter it out.
*/
final List<String> headerNames = new ArrayList<>(Collections.list(req.getHeaderNames()));
headerNames.remove("Origin");
final HttpServletRequestWrapper newReq = new HttpServletRequestWrapper(req) {
@Override
public Enumeration<String> getHeaderNames() {
return Collections.enumeration(headerNames);
}
@Override
public Enumeration<String> getHeaders(final String name) {
if ("origin".equalsIgnoreCase(name)) {
return Collections.emptyEnumeration();
} else {
return super.getHeaders(name);
}
}
@Override
public String getHeader(final String name) {
if ("origin".equalsIgnoreCase(name)) {
return null;
} else {
return super.getHeader(name);
}
}
};
chain.doFilter(newReq, response);
return;
}
}
chain.doFilter(request, response);
}
use of javax.servlet.http.HttpServletRequestWrapper in project incubator-atlas by apache.
the class AtlasAuthenticationFilter method doKerberosAuth.
/**
* This method is copied from hadoop auth lib, code added for error handling and fallback to other auth methods
*
* If the request has a valid authentication token it allows the request to continue to the target resource,
* otherwise it triggers an authentication sequence using the configured {@link org.apache.hadoop.security.authentication.server.AuthenticationHandler}.
*
* @param request the request object.
* @param response the response object.
* @param filterChain the filter chain object.
*
* @throws IOException thrown if an IO error occurred.
* @throws ServletException thrown if a processing error occurred.
*/
public void doKerberosAuth(ServletRequest request, ServletResponse response, FilterChain filterChainWrapper, FilterChain filterChain) throws IOException, ServletException {
boolean unauthorizedResponse = true;
int errCode = HttpServletResponse.SC_UNAUTHORIZED;
AuthenticationException authenticationEx = null;
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
boolean isHttps = "https".equals(httpRequest.getScheme());
AuthenticationHandler authHandler = getAuthenticationHandler();
try {
boolean newToken = false;
AuthenticationToken token;
try {
token = getToken(httpRequest);
} catch (AuthenticationException ex) {
LOG.warn("AuthenticationToken ignored: {}", ex.getMessage());
// will be sent back in a 401 unless filter authenticates
authenticationEx = ex;
token = null;
}
if (authHandler.managementOperation(token, httpRequest, httpResponse)) {
if (token == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Request [{}] triggering authentication", getRequestURL(httpRequest));
}
token = authHandler.authenticate(httpRequest, httpResponse);
if (token != null && token.getExpires() != 0 && token != AuthenticationToken.ANONYMOUS) {
token.setExpires(System.currentTimeMillis() + getValidity() * 1000);
}
newToken = true;
}
if (token != null) {
unauthorizedResponse = false;
if (LOG.isDebugEnabled()) {
LOG.debug("Request [{}] user [{}] authenticated", getRequestURL(httpRequest), token.getUserName());
}
final AuthenticationToken authToken = token;
httpRequest = new HttpServletRequestWrapper(httpRequest) {
@Override
public String getAuthType() {
return authToken.getType();
}
@Override
public String getRemoteUser() {
return authToken.getUserName();
}
@Override
public Principal getUserPrincipal() {
return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
}
};
if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
String signedToken = signer.sign(token.toString());
createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(), token.getExpires(), isHttps);
}
filterChainWrapper.doFilter(httpRequest, httpResponse);
}
} else {
unauthorizedResponse = false;
}
} catch (AuthenticationException ex) {
// exception from the filter itself is fatal
errCode = HttpServletResponse.SC_FORBIDDEN;
authenticationEx = ex;
LOG.warn("Authentication exception: {}", ex.getMessage(), ex);
}
if (unauthorizedResponse) {
if (!httpResponse.isCommitted()) {
createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, isHttps);
// present.. reset to 403 if not found..
if ((errCode == HttpServletResponse.SC_UNAUTHORIZED) && (!httpResponse.containsHeader(KerberosAuthenticator.WWW_AUTHENTICATE))) {
errCode = HttpServletResponse.SC_FORBIDDEN;
}
if (authenticationEx == null) {
// added this code for atlas error handling and fallback
if (!supportKeyTabBrowserLogin && isBrowser(httpRequest.getHeader("User-Agent"))) {
filterChain.doFilter(request, response);
} else {
boolean chk = true;
Collection<String> headerNames = httpResponse.getHeaderNames();
for (String headerName : headerNames) {
String value = httpResponse.getHeader(headerName);
if (headerName.equalsIgnoreCase("Set-Cookie") && value.startsWith("ATLASSESSIONID")) {
chk = false;
break;
}
}
String authHeader = httpRequest.getHeader("Authorization");
if (authHeader == null && chk) {
filterChain.doFilter(request, response);
} else if (authHeader != null && authHeader.startsWith("Basic")) {
filterChain.doFilter(request, response);
}
}
} else {
httpResponse.sendError(errCode, authenticationEx.getMessage());
}
}
}
}
use of javax.servlet.http.HttpServletRequestWrapper in project lucene-solr by apache.
the class MockAuthenticationPlugin method forward.
protected void forward(String user, ServletRequest req, ServletResponse rsp, FilterChain chain) throws IOException, ServletException {
if (user != null) {
final Principal p = new BasicUserPrincipal(user);
req = new HttpServletRequestWrapper((HttpServletRequest) req) {
@Override
public Principal getUserPrincipal() {
return p;
}
};
}
chain.doFilter(req, rsp);
}
Aggregations