I have a Spring websocket application that I want to access from another client.
I am using sockjs to do this.
When connection to http://localhost:8080/hello/info is attempted to open, I get a 403 (forbidden) error.
Here is my CORS conf in Spring:
#Component
public class SimpleCORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD, PATCH");
response.setHeader("Access-Control-Allow-Headers",
"Origin, Content-Type, Accept, Cookie, Connection, Accept-Encoding, Accept-Language, Content-Length, Host, Referer, User-Agent");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
If I try to use the socket from the page that Spring it self server, it works without problems. But when I do it from another client that uses that same Angular code that I have in Spring, it fails with the error above.
Here is the comparison of Request headers:
Working header:
GET /hello/info HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Cache-Control: max-age=0
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/41.0.2272.76 Chrome/41.0.2272.76 Safari/537.36
Accept: */*
Referer: http://localhost:8080/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: et-EE,et;q=0.8,en-US;q=0.6,en;q=0.4
Cookie: remember_token=Q9M8fpJa13SsrXJOUDwVAg; _test1_session=N0wvOWV5cTU3VWd2TEs0SnZ2RkVqQ0lzN2tkbndzWmlodVl0VVl5eFdsR1FvYURKMEV0cFFsU2RpK2ZiVTF6ZHZLdFJnSUY0Ukl1Nloxd29QQlNFTmFBT2ZjbVA4M1ZzUEZubDZHSWFRTjhidVlTa3JoZE9MbEhBRGg5SmhmandRWkxNSXQ1cXFLb3ZRTXFLLzZGZGp3PT0tLXZ3czlJLzZxUjloR0EwcHlrdVVwc2c9PQ%3D%3D--c152b026e7859d5e8a5e8f260b66b33a6921f3b7; _harjutus_session=eVlEeU1nWjc4QjZhM0M4bEZQQ0FtVEp6UnFCYVkzUld1bVNDMVpTK1M2SmVjMEpQZlBSWWQ0YUxLczNZeGs5cGVJbWMybWxpN0lzKzBlRGJsR1JCVnQyN21ZWWZLMDJpZU1ENHE2VlJUcVFSdnU1aUVNOUpCOW5Cdyt2QSt0K2JrcHIzME56ZURlbTBtYmlTSlozcWpYY1FLMVlhMlVFWEp3WExNUHA1azdkWFpBY3NxQnJYeC90ZTJzR0NFa2VpYnNRcnp3c0ZOTVVmUDU4N2I4Zy92SHJMTDludVJYTkJtU3E2T0lGUFUwcEQrREtUUmtsdGdkWXVRR2lvN3pXMi0tTVB3WFB2M0NURDQvZlFwbm5UWEZqUT09--5e23d496aa3ecad4f5e7343ba8e326f18304844b
Not working header:
GET /hello/info HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Cache-Control: max-age=0
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/41.0.2272.76 Chrome/41.0.2272.76 Safari/537.36
Accept: */*
Referer: http://localhost:3000/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: et-EE,et;q=0.8,en-US;q=0.6,en;q=0.4
Is the problem with the cookie header?
I did this the problematic client but nothing changed. But it should not matter also as both my Spring application and the Ruby on Rails application have exactly the same Angular code that is used to connect to the websocket.
app.config([
'$httpProvider', function($httpProvider) {
$httpProvider.defaults.withCredentials = true;
}
]);
EDIT: accessing the websocket URL in browser shows this: {"entropy":-319177751,"origins":["*:*"],"cookie_needed":true,"websocket":true}
Can the cookie_needed be turned off somehow? I fail to find anything in Spring docs for it.
You use websockets, so if you have the newest version of Spring it could be that you didn't specify the allowed origins. According to the documentation, 21.2.6 Configuring allowed origins, only same origin requests are allowed by default for websockets as of Spring 4.1.5.
Related
I had the next CORS configuration in my Spring Boot (2.4.4) application:
#Configuration
public class CORSConfiguration {
#Bean
public WebMvcConfigurer cors() {
return new WebMvcConfigurer() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
};
}
}
At some point of time I started getting the next exception:
java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
After that, I fixed my configuration according with the answer:
registry.addMapping("/**").allowedOriginPatterns("*");
After that, the problem with CORS is gone away. And as I understood, I can't use allowedOrigins("*") with allowCredentials(true). Ok, it's clear. But I didn't add allowCredentials(true) in my code at all. Perhaps this is the default value(?).
Then I decided to write my configuration the next way:
registry.addMapping("/**").allowCredentials(false).allowedOrigins("*");
And the problem with CORS and exception came back. Why Spring set allowCredentials(true) somewhere inside, despite the fact that I specified the following value as allowCredentials(false).
What am I wrong about? Or why Spring overrides the value of allowCredentials in some cases?
My failed CORS request
Request headers:
OPTIONS /list/1054/participant-list/info HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: GET
Access-Control-Request-Headers: content-type
Referer: http://localhost:13000/
Origin: http://localhost:13000
Connection: keep-alive
Response headers:
HTTP/1.1 500
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,HEAD,POST
Access-Control-Allow-Headers: content-type
Access-Control-Max-Age: 1800
Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Content-Length: 0
Date: Tue, 06 Jul 2021 14:15:16 GMT
Connection: close
Try this and make sure to add the correct origin of the client-side as well as put the needed allowed methods there. I just randomly put there
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:13000")
.allowedMethods("HEAD","GET","POST","PUT","DELETE","PATCH").allowedHeaders("*");
}
I'm having a blocking exception while requesting the servlet parts in Weblogic 12.2.1.4-dev on docker.(please note that this is working on Wildfly server)
The Java code i'm using is:
import javax.servlet.http.*;
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException {
...
Collection<Part> parts = request.getParts();
...
}
the error i'm having in the server.log:
<Oct 2, 2020 9:17:59,302 AM GMT> <Warning> <HTTP> <BEA-101394> <The exception "The request content-type is not a multipart/form-data" occurred when processing getParameter or getParameterValues from a multipart value of a ServletRequest.>
javax.servlet.ServletException: The request content-type is not a multipart/form-data
at weblogic.servlet.utils.fileupload.Multipart.getParts(Multipart.java:158)
at weblogic.servlet.internal.ServletRequestImpl$RequestParameters.getParts(ServletRequestImpl.java:2497)
at weblogic.servlet.internal.ServletRequestImpl$RequestParameters.access$3000(ServletRequestImpl.java:2181)
at weblogic.servlet.internal.ServletRequestImpl.getParts(ServletRequestImpl.java:3652)
at javax.servlet.http.HttpServletRequestWrapper.getParts(HttpServletRequestWrapper.java:375)
And the Http request details on google chrome:
// GENERAL
Request URL: http://172.21.1.1:8310/backoffice/service
Request Method: PUT
Status Code: 400 Bad Request
Remote Address: 172.1.1.1:8310
Referrer Policy: strict-origin-when-cross-origin
// REQUEST HEADERS
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-BE,en;q=0.9,fr-FR;q=0.8,fr;q=0.7,en-US;q=0.6,es;q=0.5,it;q=0.4
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 647482
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryoCBB96YNI9S3vXob
Cookie: JSESSIONID=XIjomkiRAVxEtEn0qwlILe46arjsphNNibL00t2dHEhj75oc167A!-481127499
Host: 172.1.1.1:8310
Origin: http://172.1.1.1:8310
Pragma: no-cache
Referer: http://172.1.1.1:8310/backoffice/products/edit?id=MA01
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36
X-Requested-With: XMLHttpRequest
// FORM DATA
subside-velo-pedelec25.pdf: (binary)
actionId: 98c6e900-0289-4bb6-8e98-2b967b2ee363
windowId: YbVZr0XiCFHxU7K4hUlmBJmLoXwzY6
I faced the same issue.
FileUpload's servlet implementation from WebLogic core libs only allow multipart requests under "POST" method:
private boolean isMultipart() {
if (!this.request.getMethod().toLowerCase().equals("post"))
return false;
String contentType = this.request.getContentType();
if (contentType == null)
return false;
if (contentType.toLowerCase().startsWith("multipart/form-data"))
return true;
return false;
}
If this validation fails, it will throw an exception including a message that does not have any relation with the actual error:
if (!isMultipart())
throw new ServletException("The request content-type is not a multipart/form-data");
So I switched my method from PUT to POST.
I'm trying to rebuild the session setup to a web server by a Java HttpClient application. I have chosen the incubated HttpClient provided with Java 9 and Java 10.
With Chrome I captured this headers from a single request:
General
Request URL: https://<some_url>?user_id=1176&onlyDirectUserItems=true&onlyAssignedToUser=true&show=Unresolved&itemsFilter=0
Request Method: GET
Status Code: 302 Found
Remote Address: <theProxy>:8000
Referrer Policy: no-referrer-when-downgrade
Response Headers
Connection: Keep-Alive
Content-Length: 164
Content-Type: text/html; charset=iso-8859-1
Date: Fri, 08 Jun 2018 14:33:16 GMT
Keep-Alive: timeout=300, max=100
Location: https://<another_url>:443/nesp/app/plogin?agAppNa=app_me_company_ext&c=secure/name/password/uri&target=%22https://<another-usr>/browseIssues.spr?user_id=1176&onlyDirectUserItems=true&onlyAssignedToUser=true&show=Unresolved&itemsFilter=0%22
P3p: CP="NOI"
Server: Apache
Set-Cookie: IPCZQX03224bfb75=030003000000000000000000000000008f7aed69; path=/; domain=.me.de
Via: 1.1 <host> (Access Gateway-ag-7169149846802036-13837511)
Request Headers
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7
Connection: keep-alive
Cookie: org.ditchnet.jsp.tabs.wiki=wiki-wysiwyg; ZNPCQ003-31393000=6c2f99a3; ZNPCQ003-32323200=cd188fdd
DNT: 1
Host: <host>
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
Query String Parameters
user_id: 1176
onlyDirectUserItems: true
onlyAssignedToUser: true
show: Unresolved
itemsFilter: 0
What can be seen the Response Header provides a URL (header-key: "location") which I need to grab and call next. But with my http client I fail with status-code 400 and get almost nothing
This is my code
url = "https://<some_url>?user_id=1176&onlyDirectUserItems=true&onlyAssignedToUser=true&show=Unresolved&itemsFilter=0";
HttpClient client = HttpClient.newBuilder()
.proxy(ProxySelector.of(new InetSocketAddress("<theProxy>", 8000)))
.cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ALL))
.followRedirects(HttpClient.Redirect.SAME_PROTOCOL)
.build();
HttpRequest request = HttpRequest.newBuilder()
.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0")
.header("Upgrade-Insecure-Requests", "1")
// .header("Host", "<host>")
.header("Connection", "keep-alive")
.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")
.header("Accept-Language", "de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7")
.header("Accept-Encoding", "gzip, deflate, br")
.uri(new URI(url))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString());
HttpHeaders headers = response.headers();
Map<String, List<String>> headerMap= headers.map();
for (String key : headerMap.keySet()) {
System.out.println(">"+key+"<");
for (String value : headerMap.get(key)) {
System.out.println(" " + value);
}
}
System.out.println(response.statusCode());
System.out.println(response.body());
I have no clue what might be wrong and how to proceed to get this done. I hope someone can tell me what to ty next.
What I also do not understand: I had to remove the header "Host" - because I got the response: "Your browser sent a request that this server could not understand."
The very same header as can be found in the Chrome-listing
I could get it run with Apache HttpClient. I cannot tell what is wrong with the incubated HttpClient - but there is for sure a reason that it is not a fully integrated part of the Java 9/10 delivery
For testing I want to build HttpServletRequest object from some predefined data, something like:
GET / HTTP/1.1
User-Agent: Opera/9.80 (Windows NT 6.1; WOW64; U; en) Presto/2.10.289 Version/
12.01
Host: www.foo.com
Accept: text/html, application/xml;q=0.9, application/xhtml+xml, image/png,
image/webp, image/jpeg, image/gif, image/x-xbitmap;q=0.1
Accept-Language: ru-RU,ru;q=0.9,en;q=0.8
Accept-Encoding: gzip, deflate
Pragma: no-cache
Cache-Control: no-cache
Connection: Keep-Alive
And also setup url and client address. Is there some simple way to do it?
Kirill! I think the best way in your case is using Mockito framework.
For example, you can make mock of HttpServletRequest interface. And use:
HttpServletRequest httpRequest = Mockito.mock(HttpServletRequest.class);
Mockito.when(httpRequest.getHeader("Host")).thenReturn("http://www.foo.com");
Mockito.when(httpRequest.getHeader("Referer")).thenReturn("blalba");
Mockito.when(httpRequest.getHeader("User-Agent")).thenReturn("Opera");
Mockito.when(httpRequest.getRemoteAddr()).thenReturn("127.0.0.1");
You can write a parse to read the predefined data and use HttpClient to send requests as per your requirements.
HttpClient Tutorial
I have been tryig to handle a redirect(302) in java code and now that I am done doing it by my code. I ran into an other problem in which after login, on click on any link I get logged out. So I checked my TCP Stream through wireshark and found that there are few HeaderRequests missing. After implementation of my code, Http Header are as follows :
GET /index.php/ HTTP/1.1
Host: 10.28.161.31
User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.24) Gecko/20111109 CentOS/3.6-3.el5.centos Firefox/3.6.24
Cookie: PHPSESSID=d488eea5e85afc8ec526c1a749e7ab20; path=/
Referrer: http://10.28.161.31
Cookie: $Version=0; PHPSESSID=d488eea5e85afc8ec526c1a749e7ab20; $Path=/ ???
and original Http Headers are as follows :
GET / HTTP/1.1
Host: 10.28.161.31
User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.24) Gecko/20111109 CentOS/3.6-3.el5.centos Firefox/3.6.24
Referer: http://10.28.161.31/index.php
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Cookie: PHPSESSID=978ee1e3b3696743c5c8f507a2ec7212
According to my observation, I did not copied the Header's content properly and that's why it is logging out quickly. So my question is that, how can I copy the complete content of HttpMethod to another HttpMethod? If any one can provide a code snippet or an example/tutorial would be great or If any one can give me a heads up on where I am doing things wrong, that would be appreciable.
My implementation is right here :
private HttpMethod loadHttp302Request(HttpMethod method, HttpClient client,
int status, String urlString) throws HttpException, IOException {
if (status!=302)
return null;
String[] url = urlString.split("/");
HttpMethod theMethod = new GetMethod(urlString + method.getResponseHeader("Location").getValue());
theMethod.setRequestHeader("Cookie", method.getResponseHeader("Set-Cookie")
.getValue());
theMethod.setRequestHeader("Referrer",url[0]+"//"+url[2]);
int _status = client.executeMethod(theMethod);
return theMethod;
}
HttpClient can automatically handle the redirects if you set the strategy. Follow this post on usage example Httpclient 4, error 302. How to redirect?