Solargi / shop

shop web application with springboot
1 stars 0 forks source link

Fix authentication for other endpoints and token deletion logout endpoint #29

Closed Solargi closed 21 hours ago

Solargi commented 1 month ago

solution: @SecurityRequirement(name = "bearerAuth") @GetMapping("/logout") public ResponseEntity logout(HttpServletResponse response) { ResponseCookie cookie = ResponseCookie.from("token") //set secure to true in production so that the cookie is sent only if the connection is secure //(it's using https) .secure(false) .httpOnly(true) .sameSite("Lax") .path("/api/v1/") .maxAge(0) .build(); response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());

    return ResponseEntity.ok().build();
}

/users authenticated endpoints work as expected but other authenticated endpoints don't. After logging in and getting the authentication token, springboot is unable to authenticate the frontend requests, it seems like the token is missing. LOGS:

(2024-06-03T15:17:20.192+02:00 DEBUG 1553665 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : Securing GET /api/v1/orders 2024-06-03T15:17:20.194+02:00 DEBUG 1553665 --- [nio-8080-exec-2] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext 2024-06-03T15:17:20.199+02:00 DEBUG 1553665 --- [nio-8080-exec-2] s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using Or [RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest], And [Not [MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@153c69bc, matchingMediaTypes=[text/html], useEquals=false, ignoredMediaTypes=[]]], MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@153c69bc, matchingMediaTypes=[application/atom+xml, application/x-www-form-urlencoded, application/json, application/octet-stream, application/xml, multipart/form-data, text/xml], useEquals=false, ignoredMediaTypes=[/]]], MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@153c69bc, matchingMediaTypes=[/], useEquals=true, ignoredMediaTypes=[]]] 2024-06-03T15:17:20.200+02:00 DEBUG 1553665 --- [nio-8080-exec-2] s.w.a.DelegatingAuthenticationEntryPoint : Match found! Executing com.example.shop.security.AuthenticationEntryPointNoPopUp@33b4c775)

Solargi commented 1 month ago

this is due to the path of the https only token in the cookies which is set to the default requested map in the authentication controller in this case "api/v1/users". this means that the toke is send only for requests to path that include the "api/v1/users" root. Setting the base path api/v1/ during the creation of the cookie should fix the problem.

in auth controller, add this to ResponseCookie: .path("/api/v1/")