Spring session generates session even though I am not authorized - spring

I have created an application which uses spring session. When I make a call to api which needs to be authenticated I am getting an error, which is fine but also application generates a session id. Is it a correct behaviour?
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0HTTP/1.1 401 Unauthorized
X-Powered-By: Express
Access-Control-Allow-Origin: *
x-content-type-options: nosniff
x-xss-protection: 1; mode=block
cache-control: no-cache, no-store, max-age=0, must-revalidate
pragma: no-cache
expires: 0
x-frame-options: DENY
set-cookie: SESSION=SESSION_ID; Path=/; HttpOnly
content-length: 0
date: Fri, 09 Aug 2019 17:04:46 GMT
connection: close
My authorization method looks which is called after log in:
public void authorize(final String authorizationCode, final HttpServletRequest request) {
log.info("Logging...");
final HttpSession httpSession = request.getSession();
httpSession.setAttribute("token", token);
httpSession.setAttribute("account_id", accountId);
httpSession.setAttribute("user_id", userId);
}
What is more in application.properties I set server.servlet.session.cookie.secure=true and still in cookie is only httpOnly.

Related

ResponseStatusException - response body missing

I am using
id 'org.springframework.boot' version '2.6.1'
Following is the code snippet I am using for throwing the exception
catch(Exception e){
System.out.println(e.getLocalizedMessage());
throw new ResponseStatusException(
HttpStatus.BAD_REQUEST, "something went wrong",e);
}
In response, we are getting 400 without a response body
* upload completely sent off: 100 out of 100 bytes
* Mark bundle as not supporting multiuse
< HTTP/1.1 400
< Vary: Origin
< Vary: Access-Control-Request-Method
< Vary: Access-Control-Request-Headers
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Content-Length: 0
< Date: Thu, 27 Oct 2022 14:43:38 GMT
< Connection: close
<
* Closing connection 0
UPDATE: application.properties has the following config
server.error.include-message=always
What am I missing?
Starting from 2.3, Spring Boot doesn't include an error message on the default error page. The reason is to reduce the risk of leaking information to a client.
To change the default behavior, you can set the server.error.include-message property:
server.error.include-message=always
Source:
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.3-Release-Notes#changes-to-the-default-error-pages-content

Using Postman and Soapui I get a 400 when hitting a Spring Boot endpoint, but Swagger has no problem

The endpoint is in a RestController with this signature:
#PostMapping(value = "/unclaim")
#Operation(summary = "Unclaim Tasks ")
public BaseResponse<String> claimTasks(
#RequestParam(required = true, name = "taskIds") Long taskIds[]
)
{
If I use Soap ui to the correct URL ( I know I got that right, b/c if I append another character to it, I get a 404 ) I send this payload:
{
taskIds: [ 444, 34, 55 ]
}
Doing this in SoapUI and Postman both give 400s and no explanation :
HTTP/1.1 400
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Set-Cookie: JSESSIONID=C18701F799961FEECF967457574EB914; Path=/tlmapi; HttpOnly
Content-Length: 0
Date: Fri, 02 Sep 2022 16:11:44 GMT
Connection: close
But going to the swagger-ui.html page for this controller lets me construct a request that works :
So what's the difference ? Or is there a way to see the payload that swagger is sending?
Turns out that I accidentally was using the #RequestParam annotation on the list, instead of #RequestBody. Further, the param was Required, so spring rejected it and ignored my Json payload from SoapUI and Postman.
Hope this helps someone not waste a couple of hours...

What is stopping browser to download pdf file

I am using spring boot application to download a jasper file, which is downloaded in my system, on browser. The code that I have written is:
#GetMapping("/download")
public ResponseEntity downloadFileFromLocal(HttpServletResponse response) throws JRException, SQLException, IOException {
Path path = Paths.get(System.getProperty("user.home") + "//downloads//" + "fileName.pdf");
Resource resource = null;
try {
resource = new UrlResource(path.toUri());
} catch (MalformedURLException e) {
e.printStackTrace();
}
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType("application/download"))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
This code is working perfectly fine and my file is being downloaded on browser when I try this code in a simple application i.e. practice approach. However, when I try to download the file in my main application with the same code then nothing happens. I am not sure what is stopping browser to download my pdf file in browser. The expected result is:
I think there is some problem with the response Headers.
Following is the response header for my Practice application file:
Accept-Ranges: bytes
Connection: keep-alive
Content-Disposition: attachment; filename="Daily%20Report%20For%20Site_ID%201.pdf"
Content-Length: 2869
Content-Type: application/download
Date: Mon, 27 Dec 2021 10:48:24 GMT
Keep-Alive: timeout=60
And for main application, response headers are:
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 0
Date: Mon, 27 Dec 2021 11:28:33 GMT
Expires: 0
Pragma: no-cache
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

Why Spring Boot application does not work with relative quality factor of HTTP?

Lets suppose I have a Spring Boot application:
dependencies {
implementation("org.springframework.boot:spring-boot-starter-webflux:2.4.0")
}
with a simple RestController:
#RestController
class TestController {
#PostMapping("/test")
suspend fun test(#RequestBody request: Map<String, String>) {
throw RuntimeException("test")
}
}
When I use httpie client to make requests, then the result looks like:
➜ ~ http post :8080/test param=value --verbose
POST /test HTTP/1.1
Accept: application/json, */*;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 18
Content-Type: application/json
Host: localhost:8080
User-Agent: HTTPie/2.3.0
{
"param": "value"
}
HTTP/1.1 500 Internal Server Error
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 309
Content-Type: text/html;charset=UTF-8
Expires: 0
Pragma: no-cache
Referrer-Policy: no-referrer
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1 ; mode=block
<html><body><h1>Whitelabel Error Page</h1><p>This application has no configured error view, so you are seeing this as a fallback.</p><div id='created'>Wed Dec 09 22:24:52 MSK 2020</div><div>[906bb33e-5] There was an unexpected error (type=Internal Server Error, status=500).</div><div>test</div></body></html>
When I use cURL:
➜ ~ curl -XPOST localhost:8080/test -d '{"param": "value"}' -H "Content-type: application/json" -v
Note: Unnecessary use of -X or --request, POST is already inferred.
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> POST /test HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.64.1
> Accept: */*
> Content-type: application/json
> Content-Length: 18
>
* upload completely sent off: 18 out of 18 bytes
< HTTP/1.1 500 Internal Server Error
< Content-Type: application/json
< Content-Length: 170
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Content-Type-Options: nosniff
< X-Frame-Options: DENY
< X-XSS-Protection: 1 ; mode=block
< Referrer-Policy: no-referrer
<
* Connection #0 to host localhost left intact
{"timestamp":1607541989698,"path":"/test","status":500,"error":"Internal Server Error","message":"test","requestId":"7f249f68-9","exception":"java.lang.RuntimeException"}* Closing connection 0
The difference in header Accept. Httpie uses Accept: application/json, */*;q=0.5 header with relative quality factor 0.5 and, despite the fact that I requested JSON if possible (and it's possible), the application returns HTML representation.
Is it how Spring Boot should work and I do something wrong?
UPD: Everything works fine with Tomcat (spring-boot-starter-web). After some debugging I found that, when Tomcat used, errors are handled by org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController and for Netty it is org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler. It looks like the source of misbehavior is here: when MediaType.ALL is removed from acceptedMediaTypes .

Google OAuth 2: response_type error on token request

I am trying to return an OAuth 2 response code for an OAuth response token. However, my request returns the following error which has zero results in google. I tried changing response_type to "token" instead of "code" but that didn't work either.
OAuth 2 parameters can only have a single value: response_type
Request Details:
scope=https://www.googleapis.com/auth/userinfo.email
client_secret=_____
response_type=code
grant_type=authorization_code
redirect_uri=http://localhost/folder/
client_id=____.apps.googleusercontent.com
code=_____
I'm sending this second-step payload to POST https://accounts.google.com/o/oauth2/auth
What is wrong with my request?
Edit
I just realized that there is the https://accounts.google.com/o/oauth2/token URL that should be used for this request. However, changing to that URL now gives:
HTTP/1.0 400 Bad Request
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Date: Fri, 27 Jul 2012 22:44:35 GMT
Content-Type: application/json
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Server: GSE
{
"error" : "invalid_request"
}
Edit 2
Removing the response_type and changing the URL like above solved this.
After receiving the authorization code you have to ask '/o/oauth2/token' for the access token. This request takes no 'scope' and no 'response_type' parameters. See the Google documentation for more details.
After trying out a couple of methods, the required parameters to make the OAUTH2 call are
redirect_uri, response_type, scope, client_id. I kept on debugging the oauth call based on the error report I received.

Resources