This question already has answers here:
How can I know if the request to the servlet was executed using HTTP or HTTPS?
(3 answers)
Closed 6 years ago.
I have a Restful Web Service written in Java:
Example:
#GET
#PATH("/foo")
public Response getFoo(){
...
}
and a filter
public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain) {
....
}
How can i make sure that incoming requests and sent responses from my REST API are transported by HTTPS?
If you have access to ServletRequest, you can use ServletRequest.isSecure to determine whether it was HTTPS or not.
Be careful, if your application gets deployed behind some frontend servers that extract HTTPS for you, you have to do something different. Usually check some headers or similar.
Related
We have a embedded Jetty 10.0.12 server, configure everything programmably (no web.xml) and already have a few servlets registered. We want to add a new servlet for an internal API. I have already done this. We now want to secure it. Security would be pretty simple: if the request did not come from within the server, reject it. This is good enough because we employ other security standards in the other servlets. I know where to start: create and register a filter:
public class InternalFilter implements Filter {
#Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
// TODO: Check if request is internal.
// I.e., came from another registered servlet in the same JVM.
// If it is internal, then `chain.doFilter`.
}
}
I do not know how to proceed from here.
I'll start by assuming that "internal" means you are using either RequestDispatcher.include() or RequestDispatcher.forward().
If so, then you can check the HttpServletRequest.getDispatcherType() value.
Value
Meaning
DispatcherType.FORWARD
Request arrived from a call to RequestDispatcher.forward().
DispatcherType.INCLUDE
Request arrived from a call to RequestDispatcher.include().
DispatcherType.REQUEST
Request arrived from the beginning of the server handling tree.
DispatcherType.ASYNC
Request arrived from call to HttpServletRequest.startAsync()
DispatcherType.ERROR
Request arrived from error handling (either an unhandled exception, or from a call to HttpServletResponse.sendError()
How can i create a full web application with Java and React without having to create a rest API, not even a private API with username:password authentication.
I want it to be as it is created with JSP.
Is it possible call Java methods with react locally ?
Or even creating a restfull API that can only be called locally
Thank you
I don't think it's possible to communicate with Java in a client library such as React without having to create a HTTP API.
But you could make one and add a bit of extra layer of security to ensure that only your application could call your Java API by checking the remote address of each call and verifying that's the caller is indeed your server.
You can do this in Java using the getRemoteAddr() method from the HttpServletRequest object.
The best way to do this is to create a filter class that map all the API links and verify the remote address in each calls and then decide if it should allow it or not.
Here's an example:
import javax.servlet.*;
public class RequestFilter implements Filter{
public void init(FilterConfig config) throws ServletException {}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)req;
String callerIp = request.getRemoteAddr();
if(callerIp.equalsIgnoreCase("MY-SERVER-IP-ADDRESS")) {
chain.doFilter(req, res);
}
else {
((HttpServletResponse)res).sendError(HttpServletResponse.SC_FORBIDDEN, "Access denied !");
return;
}
}
public void destroy() {}
}
Replace "MY-SERVER-IP-ADDRESS" with your server ip.
And to map all the calls, set the filter tag in your web.xml as follows:
<filter>
<filter-name>RequestFilter</filter-name>
<filter-class>com.myPackage.requestFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>RequestFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
This should satisfy your need, but if you found another way please share it with us.
the first request is no, as far as I'm aware. But as for the local rest api, I know most web servers can check CORS headers and restrict to only serve certain origins on answering requests. So whichever JRE Web Server you're using, check it's API for accessing the origin in the request header, and route those to the rest code.
This question already has answers here:
Design Patterns web based applications [closed]
(5 answers)
Closed 6 years ago.
I want to understand, If request has to be processed through multiple functions-
is it good to forward through multiple Servlets OR
implement as object methods
Example
req.getRequestDispatcher("LoadSession").forward(req, resp);
req.getRequestDispatcher("AuthoriseRoles").forward(req, resp);
req.getRequestDispatcher("Boot").forward(req, resp);
OR
sessionLoader.loadSession(req,res);
authoriseService.authoriseRoles(req,res);
bootService.boot(req, res);
I assume you are at the phase of designing an API. According to REST design principles, the url should reflect the resource that is handled or requested and the HTTP method should reflect what action is required to be taken on the resource.
So, instead of /LoadSession and having the session id as query param in the Http request, it should be GET /session/{id} for example GET /session/e841092fa2194340bc40 (I am assuming LoadSession is a request to return an existing session)
You might ask yourself what is the advantage of following this design. It is that there are several libraries and frameworks that are able to parse incoming HTTP requests and take care of the routing for you (for example, Jersey is the reference JAX-RS implementation, JAX-RS being JavaEE's REST standard) . So instead of writing a servlet as you mentioned, you write the class that represents the resource and methods that are fired according to the HTTP method. you tie it all together with annotations:
#Path("/session")
import javax.ws.rs.*;
import javax.ws.rs.core.*;
#Produces({MediaType.APPLICATION_JSON})
public class SessionHandler
{
#Context
private HttpServletRequest httpRequest;
#Context
private HttpServletResponse httpResponse;
#GET
#Path("{id}")
public Session load(#PathParam("id") String id) {
...
I´m developing a Web Service, using Glassfish, using SOAP. I have several web methods, and I want to get introduce my webmethod name and his parameters to http head request.
For example:
I have this path:
context: WebServices
webMethod: makeSomething
parameters:a=2
So I create a class named ProfilingFilter:
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, javax.servlet.ServletException {
if (request.getContentLength() != -1 && context != null) {
((HttpServletResponse) response).addHeader("Operation", -->PATH+PARAMETERS);
// ((HttpServletResponse) response).addHeader("Operation", -->makeSomething?a=2);
}
}
It´s possible to use servlet response or servlet request to get this information?
If not, How can I do this?
You will need to access the HTTP request body. There is only one caveat: You can read a stream only once which means you will have to do some tricks in order to keep the SOAP request working. Take a look here:
http://wetfeetblog.com/servlet-filer-to-log-request-and-response-details-and-payload/431
This example covers reading a HTTP request and then passing the original data down the filter chain.
HTH, Mark
Why aren't cookies able to be referenced from a servlet filter? It just seems beyond me that Java EE wouldn't allow you to sanitize cookie values:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws ServletException, IOException {
request.
}
ServletRequest does not support getCookies (as is the case with HttpServletRequest).
In order to get the cookies you need to cast it to an HttpServletRequest.
HttpServletRequest httpReq = (HttpServletRequest) request;
The reason that ServletResponse class doesn't support cookies is because the protocol isn't necessarly http in a ServletRequest, you can't be sure there are Cookies. Cookies are an Http thing.
Servlets aren't required to be accessed via the HTTP protocol. Therefore, your servlet does not have to be an HttpServlet - it may be a servlet that sends out specific documents via FTP, for example. Because of this, the basic properties of a servlet are encapsulated in the ServletRequest and ServletResponse interfaces, but if you know that your servlet is an HTTPServlet, you may downcast these to HttpServletRequest and HttpServletResponse respectively with no chance of a ClassCastException as long as your Servlet is truly an HttpServlet.
You do know that you can actually cast it to HttpServletRequest, right? :-)