use of org.eclipse.jetty.util.MultiMap in project blade by biezhi.
the class FormAuthenticator method validateRequest.
/* ------------------------------------------------------------ */
@Override
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
Request base_request = Request.getBaseRequest(request);
Response base_response = base_request.getResponse();
String uri = request.getRequestURI();
if (uri == null)
uri = URIUtil.SLASH;
mandatory |= isJSecurityCheck(uri);
if (!mandatory)
return new DeferredAuthentication(this);
if (isLoginOrErrorPage(URIUtil.addPaths(request.getServletPath(), request.getPathInfo())) && !DeferredAuthentication.isDeferred(response))
return new DeferredAuthentication(this);
HttpSession session = request.getSession(true);
try {
// Handle a request for authentication.
if (isJSecurityCheck(uri)) {
final String username = request.getParameter(__J_USERNAME);
final String password = request.getParameter(__J_PASSWORD);
UserIdentity user = login(username, password, request);
LOG.debug("jsecuritycheck {} {}", username, user);
session = request.getSession(true);
if (user != null) {
// Redirect to original request
String nuri;
FormAuthentication form_auth;
synchronized (session) {
nuri = (String) session.getAttribute(__J_URI);
if (nuri == null || nuri.length() == 0) {
nuri = request.getContextPath();
if (nuri.length() == 0)
nuri = URIUtil.SLASH;
}
form_auth = new FormAuthentication(getAuthMethod(), user);
}
LOG.debug("authenticated {}->{}", form_auth, nuri);
response.setContentLength(0);
int redirectCode = (base_request.getHttpVersion().getVersion() < HttpVersion.HTTP_1_1.getVersion() ? HttpServletResponse.SC_MOVED_TEMPORARILY : HttpServletResponse.SC_SEE_OTHER);
base_response.sendRedirect(redirectCode, response.encodeRedirectURL(nuri));
return form_auth;
}
// not authenticated
if (LOG.isDebugEnabled())
LOG.debug("Form authentication FAILED for " + StringUtil.printable(username));
if (_formErrorPage == null) {
LOG.debug("auth failed {}->403", username);
if (response != null)
response.sendError(HttpServletResponse.SC_FORBIDDEN);
} else if (_dispatch) {
LOG.debug("auth failed {}=={}", username, _formErrorPage);
RequestDispatcher dispatcher = request.getRequestDispatcher(_formErrorPage);
response.setHeader(HttpHeader.CACHE_CONTROL.asString(), HttpHeaderValue.NO_CACHE.asString());
response.setDateHeader(HttpHeader.EXPIRES.asString(), 1);
dispatcher.forward(new FormRequest(request), new FormResponse(response));
} else {
LOG.debug("auth failed {}->{}", username, _formErrorPage);
int redirectCode = (base_request.getHttpVersion().getVersion() < HttpVersion.HTTP_1_1.getVersion() ? HttpServletResponse.SC_MOVED_TEMPORARILY : HttpServletResponse.SC_SEE_OTHER);
base_response.sendRedirect(redirectCode, response.encodeRedirectURL(URIUtil.addPaths(request.getContextPath(), _formErrorPage)));
}
return Authentication.SEND_FAILURE;
}
// Look for cached authentication
Authentication authentication = (Authentication) session.getAttribute(SessionAuthentication.__J_AUTHENTICATED);
if (authentication != null) {
// Has authentication been revoked?
if (authentication instanceof User && _loginService != null && !_loginService.validate(((User) authentication).getUserIdentity())) {
LOG.debug("auth revoked {}", authentication);
session.removeAttribute(SessionAuthentication.__J_AUTHENTICATED);
} else {
synchronized (session) {
String j_uri = (String) session.getAttribute(__J_URI);
if (j_uri != null) {
//check if the request is for the same url as the original and restore
//params if it was a post
LOG.debug("auth retry {}->{}", authentication, j_uri);
StringBuffer buf = request.getRequestURL();
if (request.getQueryString() != null)
buf.append("?").append(request.getQueryString());
if (j_uri.equals(buf.toString())) {
MultiMap<String> j_post = (MultiMap<String>) session.getAttribute(__J_POST);
if (j_post != null) {
LOG.debug("auth rePOST {}->{}", authentication, j_uri);
base_request.setContentParameters(j_post);
}
session.removeAttribute(__J_URI);
session.removeAttribute(__J_METHOD);
session.removeAttribute(__J_POST);
}
}
}
LOG.debug("auth {}", authentication);
return authentication;
}
}
// if we can't send challenge
if (DeferredAuthentication.isDeferred(response)) {
LOG.debug("auth deferred {}", session.getId());
return Authentication.UNAUTHENTICATED;
}
// remember the current URI
synchronized (session) {
// But only if it is not set already, or we save every uri that leads to a login form redirect
if (session.getAttribute(__J_URI) == null || _alwaysSaveUri) {
StringBuffer buf = request.getRequestURL();
if (request.getQueryString() != null)
buf.append("?").append(request.getQueryString());
session.setAttribute(__J_URI, buf.toString());
session.setAttribute(__J_METHOD, request.getMethod());
if (MimeTypes.Type.FORM_ENCODED.is(req.getContentType()) && HttpMethod.POST.is(request.getMethod())) {
MultiMap<String> formParameters = new MultiMap<>();
base_request.extractFormParameters(formParameters);
session.setAttribute(__J_POST, formParameters);
}
}
}
// send the the challenge
if (_dispatch) {
LOG.debug("challenge {}=={}", session.getId(), _formLoginPage);
RequestDispatcher dispatcher = request.getRequestDispatcher(_formLoginPage);
response.setHeader(HttpHeader.CACHE_CONTROL.asString(), HttpHeaderValue.NO_CACHE.asString());
response.setDateHeader(HttpHeader.EXPIRES.asString(), 1);
dispatcher.forward(new FormRequest(request), new FormResponse(response));
} else {
LOG.debug("challenge {}->{}", session.getId(), _formLoginPage);
int redirectCode = (base_request.getHttpVersion().getVersion() < HttpVersion.HTTP_1_1.getVersion() ? HttpServletResponse.SC_MOVED_TEMPORARILY : HttpServletResponse.SC_SEE_OTHER);
base_response.sendRedirect(redirectCode, response.encodeRedirectURL(URIUtil.addPaths(request.getContextPath(), _formLoginPage)));
}
return Authentication.SEND_CONTINUE;
} catch (IOException | ServletException e) {
throw new ServerAuthException(e);
}
}
use of org.eclipse.jetty.util.MultiMap in project vespa by vespa-engine.
the class HttpRequest method getUriQueryParameters.
private static Map<String, List<String>> getUriQueryParameters(URI uri) {
MultiMap<String> queryParameters = new MultiMap<>();
new HttpURI(uri).decodeQueryTo(queryParameters);
// Do a deep copy so we do not leak Jetty classes outside
Map<String, List<String>> deepCopiedQueryParameters = new HashMap<>();
for (Map.Entry<String, List<String>> entry : queryParameters.entrySet()) {
deepCopiedQueryParameters.put(entry.getKey(), new ArrayList<>(entry.getValue()));
}
return deepCopiedQueryParameters;
}
use of org.eclipse.jetty.util.MultiMap in project SpringStepByStep by JavaProgrammerLB.
the class WebConfig method setupRoutes.
private void setupRoutes() {
/*
* Shows a users timeline or if no user is logged in,
* it will redirect to the public timeline.
* This timeline shows the user's messages as well
* as all the messages of followed users.
*/
get("/", (req, res) -> {
User user = getAuthenticatedUser(req);
Map<String, Object> map = new HashMap<>();
map.put("pageTitle", "Timeline");
map.put("user", user);
List<Message> messages = service.getUserFullTimelineMessages(user);
map.put("messages", messages);
return new ModelAndView(map, "timeline.ftl");
}, new FreeMarkerEngine());
before("/", (req, res) -> {
User user = getAuthenticatedUser(req);
if (user == null) {
res.redirect("/public");
halt();
}
});
/*
* Displays the latest messages of all users.
*/
get("/public", (req, res) -> {
User user = getAuthenticatedUser(req);
Map<String, Object> map = new HashMap<>();
map.put("pageTitle", "Public Timeline");
map.put("user", user);
List<Message> messages = service.getPublicTimelineMessages();
map.put("messages", messages);
return new ModelAndView(map, "timeline.ftl");
}, new FreeMarkerEngine());
/*
* Displays a user's tweets.
*/
get("/t/:username", (req, res) -> {
String username = req.params(":username");
User profileUser = service.getUserbyUsername(username);
User authUser = getAuthenticatedUser(req);
boolean followed = false;
if (authUser != null) {
followed = service.isUserFollower(authUser, profileUser);
}
List<Message> messages = service.getUserTimelineMessages(profileUser);
Map<String, Object> map = new HashMap<>();
map.put("pageTitle", username + "'s Timeline");
map.put("user", authUser);
map.put("profileUser", profileUser);
map.put("followed", followed);
map.put("messages", messages);
return new ModelAndView(map, "timeline.ftl");
}, new FreeMarkerEngine());
/*
* Checks if the user exists
*/
before("/t/:username", (req, res) -> {
String username = req.params(":username");
User profileUser = service.getUserbyUsername(username);
if (profileUser == null) {
halt(404, "User not Found");
}
});
/*
* Adds the current user as follower of the given user.
*/
get("/t/:username/follow", (req, res) -> {
String username = req.params(":username");
User profileUser = service.getUserbyUsername(username);
User authUser = getAuthenticatedUser(req);
service.followUser(authUser, profileUser);
res.redirect("/t/" + username);
return null;
});
/*
* Checks if the user is authenticated and the user to follow exists
*/
before("/t/:username/follow", (req, res) -> {
String username = req.params(":username");
User authUser = getAuthenticatedUser(req);
User profileUser = service.getUserbyUsername(username);
if (authUser == null) {
res.redirect("/login");
halt();
} else if (profileUser == null) {
halt(404, "User not Found");
}
});
/*
* Removes the current user as follower of the given user.
*/
get("/t/:username/unfollow", (req, res) -> {
String username = req.params(":username");
User profileUser = service.getUserbyUsername(username);
User authUser = getAuthenticatedUser(req);
service.unfollowUser(authUser, profileUser);
res.redirect("/t/" + username);
return null;
});
/*
* Checks if the user is authenticated and the user to unfollow exists
*/
before("/t/:username/unfollow", (req, res) -> {
String username = req.params(":username");
User authUser = getAuthenticatedUser(req);
User profileUser = service.getUserbyUsername(username);
if (authUser == null) {
res.redirect("/login");
halt();
} else if (profileUser == null) {
halt(404, "User not Found");
}
});
/*
* Presents the login form or redirect the user to
* her timeline if it's already logged in
*/
get("/login", (req, res) -> {
Map<String, Object> map = new HashMap<>();
if (req.queryParams("r") != null) {
map.put("message", "You were successfully registered and can login now");
}
return new ModelAndView(map, "login.ftl");
}, new FreeMarkerEngine());
/*
* Logs the user in.
*/
post("/login", (req, res) -> {
Map<String, Object> map = new HashMap<>();
User user = new User();
try {
MultiMap<String> params = new MultiMap<String>();
UrlEncoded.decodeTo(req.body(), params, "UTF-8", -1);
BeanUtils.populate(user, params);
} catch (Exception e) {
halt(501);
return null;
}
LoginResult result = service.checkUser(user);
if (result.getUser() != null) {
addAuthenticatedUser(req, result.getUser());
res.redirect("/");
halt();
} else {
map.put("error", result.getError());
}
map.put("username", user.getUsername());
return new ModelAndView(map, "login.ftl");
}, new FreeMarkerEngine());
/*
* Checks if the user is already authenticated
*/
before("/login", (req, res) -> {
User authUser = getAuthenticatedUser(req);
if (authUser != null) {
res.redirect("/");
halt();
}
});
/*
* Presents the register form or redirect the user to
* her timeline if it's already logged in
*/
get("/register", (req, res) -> {
Map<String, Object> map = new HashMap<>();
return new ModelAndView(map, "register.ftl");
}, new FreeMarkerEngine());
/*
* Registers the user.
*/
post("/register", (req, res) -> {
Map<String, Object> map = new HashMap<>();
User user = new User();
try {
MultiMap<String> params = new MultiMap<String>();
UrlEncoded.decodeTo(req.body(), params, "UTF-8", -1);
BeanUtils.populate(user, params);
} catch (Exception e) {
halt(501);
return null;
}
String error = user.validate();
if (StringUtils.isEmpty(error)) {
User existingUser = service.getUserbyUsername(user.getUsername());
if (existingUser == null) {
service.registerUser(user);
res.redirect("/login?r=1");
halt();
} else {
error = "The username is already taken";
}
}
map.put("error", error);
map.put("username", user.getUsername());
map.put("email", user.getEmail());
return new ModelAndView(map, "register.ftl");
}, new FreeMarkerEngine());
/*
* Checks if the user is already authenticated
*/
before("/register", (req, res) -> {
User authUser = getAuthenticatedUser(req);
if (authUser != null) {
res.redirect("/");
halt();
}
});
/*
* Registers a new message for the user.
*/
post("/message", (req, res) -> {
User user = getAuthenticatedUser(req);
MultiMap<String> params = new MultiMap<String>();
UrlEncoded.decodeTo(req.body(), params, "UTF-8", -1);
Message m = new Message();
m.setUserId(user.getId());
m.setPubDate(new Date());
BeanUtils.populate(m, params);
service.addMessage(m);
res.redirect("/");
return null;
});
/*
* Checks if the user is authenticated
*/
before("/message", (req, res) -> {
User authUser = getAuthenticatedUser(req);
if (authUser == null) {
res.redirect("/login");
halt();
}
});
/*
* Logs the user out and redirects to the public timeline
*/
get("/logout", (req, res) -> {
removeAuthenticatedUser(req);
res.redirect("/public");
return null;
});
}
use of org.eclipse.jetty.util.MultiMap in project jetty.project by eclipse.
the class CGI method exec.
/**
* executes the CGI process
*
* @param command the command to execute, this command is prefixed by
* the context parameter "commandPrefix".
* @param pathInfo The PATH_INFO to process,
* see http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getPathInfo%28%29. Cannot be null
* @param req the HTTP request
* @param res the HTTP response
* @throws IOException if the execution of the CGI process throws
*/
private void exec(File command, String pathInfo, HttpServletRequest req, HttpServletResponse res) throws IOException {
assert req != null;
assert res != null;
assert pathInfo != null;
assert command != null;
if (LOG.isDebugEnabled()) {
LOG.debug("CGI: script is " + command);
LOG.debug("CGI: pathInfo is " + pathInfo);
}
String bodyFormEncoded = null;
if ((HttpMethod.POST.is(req.getMethod()) || HttpMethod.PUT.is(req.getMethod())) && "application/x-www-form-urlencoded".equals(req.getContentType())) {
MultiMap<String> parameterMap = new MultiMap<>();
Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String parameterName = names.nextElement();
parameterMap.addValues(parameterName, req.getParameterValues(parameterName));
}
bodyFormEncoded = UrlEncoded.encode(parameterMap, Charset.forName(req.getCharacterEncoding()), true);
}
EnvList env = new EnvList(_env);
// these ones are from "The WWW Common Gateway Interface Version 1.1"
// look at :
// http://Web.Golux.Com/coar/cgi/draft-coar-cgi-v11-03-clean.html#6.1.1
env.set("AUTH_TYPE", req.getAuthType());
int contentLen = req.getContentLength();
if (contentLen < 0)
contentLen = 0;
if (bodyFormEncoded != null) {
env.set("CONTENT_LENGTH", Integer.toString(bodyFormEncoded.length()));
} else {
env.set("CONTENT_LENGTH", Integer.toString(contentLen));
}
env.set("CONTENT_TYPE", req.getContentType());
env.set("GATEWAY_INTERFACE", "CGI/1.1");
if (pathInfo.length() > 0) {
env.set("PATH_INFO", pathInfo);
}
String pathTranslated = req.getPathTranslated();
if ((pathTranslated == null) || (pathTranslated.length() == 0))
pathTranslated = pathInfo;
env.set("PATH_TRANSLATED", pathTranslated);
env.set("QUERY_STRING", req.getQueryString());
env.set("REMOTE_ADDR", req.getRemoteAddr());
env.set("REMOTE_HOST", req.getRemoteHost());
// The identity information reported about the connection by a
// RFC 1413 [11] request to the remote agent, if
// available. Servers MAY choose not to support this feature, or
// not to request the data for efficiency reasons.
// "REMOTE_IDENT" => "NYI"
env.set("REMOTE_USER", req.getRemoteUser());
env.set("REQUEST_METHOD", req.getMethod());
String scriptPath;
String scriptName;
// use docRoot for scriptPath, too
if (_cgiBinProvided) {
scriptPath = command.getAbsolutePath();
scriptName = scriptPath.substring(_docRoot.getAbsolutePath().length());
} else {
String requestURI = req.getRequestURI();
scriptName = requestURI.substring(0, requestURI.length() - pathInfo.length());
scriptPath = getServletContext().getRealPath(scriptName);
}
env.set("SCRIPT_FILENAME", scriptPath);
env.set("SCRIPT_NAME", scriptName);
env.set("SERVER_NAME", req.getServerName());
env.set("SERVER_PORT", Integer.toString(req.getServerPort()));
env.set("SERVER_PROTOCOL", req.getProtocol());
env.set("SERVER_SOFTWARE", getServletContext().getServerInfo());
Enumeration<String> enm = req.getHeaderNames();
while (enm.hasMoreElements()) {
String name = enm.nextElement();
if (name.equalsIgnoreCase("Proxy"))
continue;
String value = req.getHeader(name);
env.set("HTTP_" + name.toUpperCase(Locale.ENGLISH).replace('-', '_'), value);
}
// these extra ones were from printenv on www.dev.nomura.co.uk
env.set("HTTPS", (req.isSecure() ? "ON" : "OFF"));
// "DOCUMENT_ROOT" => root + "/docs",
// "SERVER_URL" => "NYI - http://us0245",
// "TZ" => System.getProperty("user.timezone"),
// are we meant to decode args here? or does the script get them
// via PATH_INFO? if we are, they should be decoded and passed
// into exec here...
String absolutePath = command.getAbsolutePath();
String execCmd = absolutePath;
// escape the execCommand
if (execCmd.length() > 0 && execCmd.charAt(0) != '"' && execCmd.contains(" "))
execCmd = "\"" + execCmd + "\"";
if (_cmdPrefix != null)
execCmd = _cmdPrefix + " " + execCmd;
LOG.debug("Environment: " + env.getExportString());
LOG.debug("Command: " + execCmd);
final Process p = Runtime.getRuntime().exec(execCmd, env.getEnvArray(), _docRoot);
// hook processes input to browser's output (async)
if (bodyFormEncoded != null)
writeProcessInput(p, bodyFormEncoded);
else if (contentLen > 0)
writeProcessInput(p, req.getInputStream(), contentLen);
// hook processes output to browser's input (sync)
// if browser closes stream, we should detect it and kill process...
OutputStream os = null;
AsyncContext async = req.startAsync();
try {
async.start(new Runnable() {
@Override
public void run() {
try {
IO.copy(p.getErrorStream(), System.err);
} catch (IOException e) {
LOG.warn(e);
}
}
});
// read any headers off the top of our input stream
// NOTE: Multiline header items not supported!
String line = null;
InputStream inFromCgi = p.getInputStream();
// while ((line=br.readLine())!=null)
while ((line = getTextLineFromStream(inFromCgi)).length() > 0) {
if (!line.startsWith("HTTP")) {
int k = line.indexOf(':');
if (k > 0) {
String key = line.substring(0, k).trim();
String value = line.substring(k + 1).trim();
if ("Location".equals(key)) {
res.sendRedirect(res.encodeRedirectURL(value));
} else if ("Status".equals(key)) {
String[] token = value.split(" ");
int status = Integer.parseInt(token[0]);
res.setStatus(status);
} else {
// add remaining header items to our response header
res.addHeader(key, value);
}
}
}
}
// copy cgi content to response stream...
os = res.getOutputStream();
IO.copy(inFromCgi, os);
p.waitFor();
if (!_ignoreExitState) {
int exitValue = p.exitValue();
if (0 != exitValue) {
LOG.warn("Non-zero exit status (" + exitValue + ") from CGI program: " + absolutePath);
if (!res.isCommitted())
res.sendError(500, "Failed to exec CGI");
}
}
} catch (IOException e) {
// browser has probably closed its input stream - we
// terminate and clean up...
LOG.debug("CGI: Client closed connection!", e);
} catch (InterruptedException ie) {
LOG.debug("CGI: interrupted!");
} finally {
if (os != null) {
try {
os.close();
} catch (Exception e) {
LOG.debug(e);
}
}
p.destroy();
// LOG.debug("CGI: terminated!");
async.complete();
}
}
use of org.eclipse.jetty.util.MultiMap in project jetty.project by eclipse.
the class MultiPartFilter method doFilter.
/* ------------------------------------------------------------------------------- */
/**
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
* javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest srequest = (HttpServletRequest) request;
if (srequest.getContentType() == null || !srequest.getContentType().startsWith("multipart/form-data")) {
chain.doFilter(request, response);
return;
}
String content_type = srequest.getContentType();
//Get current parameters so we can merge into them
MultiMap params = new MultiMap();
for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
Object value = entry.getValue();
if (value instanceof String[])
params.addValues(entry.getKey(), (String[]) value);
else
params.add(entry.getKey(), value);
}
MultipartConfigElement config = new MultipartConfigElement(tempdir.getCanonicalPath(), _maxFileSize, _maxRequestSize, _fileOutputBuffer);
MultiPartInputStreamParser mpis = new MultiPartInputStreamParser(request.getInputStream(), content_type, config, tempdir);
mpis.setDeleteOnExit(_deleteFiles);
mpis.setWriteFilesWithFilenames(_writeFilesWithFilenames);
request.setAttribute(MULTIPART, mpis);
try {
Collection<Part> parts = mpis.getParts();
if (parts != null) {
Iterator<Part> itor = parts.iterator();
while (itor.hasNext() && params.size() < _maxFormKeys) {
Part p = itor.next();
if (LOG.isDebugEnabled())
LOG.debug("{}", p);
MultiPartInputStreamParser.MultiPart mp = (MultiPartInputStreamParser.MultiPart) p;
if (mp.getFile() != null) {
request.setAttribute(mp.getName(), mp.getFile());
if (mp.getContentDispositionFilename() != null) {
params.add(mp.getName(), mp.getContentDispositionFilename());
if (mp.getContentType() != null)
params.add(mp.getName() + CONTENT_TYPE_SUFFIX, mp.getContentType());
}
} else {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
IO.copy(p.getInputStream(), bytes);
params.add(p.getName(), bytes.toByteArray());
if (p.getContentType() != null)
params.add(p.getName() + CONTENT_TYPE_SUFFIX, p.getContentType());
}
}
}
// handle request
chain.doFilter(new Wrapper(srequest, params), response);
} finally {
deleteFiles(request);
}
}
Aggregations