Return JSON error bodies for auth and exceptions
All checks were successful
build-and-deploy / build-deploy (push) Successful in 27s

This commit is contained in:
androidlover5842
2026-01-27 02:52:08 +05:30
parent 7f7e164acf
commit 188738e28b
2 changed files with 99 additions and 4 deletions

View File

@@ -9,11 +9,15 @@ import org.springframework.security.web.SecurityFilterChain
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
import org.springframework.security.web.authentication.HttpStatusEntryPoint
import org.springframework.http.HttpStatus
import com.fasterxml.jackson.databind.ObjectMapper
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
@Configuration(proxyBeanMethods = false)
@EnableMethodSecurity
class SecurityConfig(
private val firebaseAuthFilter: FirebaseAuthFilter
private val firebaseAuthFilter: FirebaseAuthFilter,
private val objectMapper: ObjectMapper
) {
@Bean
fun filterChain(http: HttpSecurity): SecurityFilterChain {
@@ -25,9 +29,11 @@ class SecurityConfig(
it.anyRequest().authenticated()
}
.exceptionHandling {
it.authenticationEntryPoint(HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
it.accessDeniedHandler { _, response, _ ->
response.sendError(HttpStatus.FORBIDDEN.value(), "Forbidden")
it.authenticationEntryPoint { request, response, _ ->
writeError(response, request, HttpStatus.UNAUTHORIZED, "Unauthorized")
}
it.accessDeniedHandler { request, response, _ ->
writeError(response, request, HttpStatus.FORBIDDEN, "Forbidden")
}
}
.httpBasic { it.disable() }
@@ -35,4 +41,22 @@ class SecurityConfig(
.addFilterBefore(firebaseAuthFilter, UsernamePasswordAuthenticationFilter::class.java)
return http.build()
}
private fun writeError(
response: HttpServletResponse,
request: HttpServletRequest,
status: HttpStatus,
message: String
) {
if (response.isCommitted) return
response.status = status.value()
response.contentType = "application/json"
val body = mapOf(
"status" to status.value(),
"error" to status.reasonPhrase,
"message" to message,
"path" to request.requestURI
)
response.writer.use { it.write(objectMapper.writeValueAsString(body)) }
}
}