Video tayyorlanmoqda

Middle 🌱 Spring

Spring Security'da 401 va 403 javoblarini o'z JSON formatingizda qaytarish uchun nimani sozlaysiz?

Filter'da chiqqan xato @RestControllerAdvice'ga yetib bormaydi. Shuning uchun 401 uchun AuthenticationEntryPoint, 403 uchun AccessDeniedHandler yozib, ularni exceptionHandling() orqali SecurityFilterChain'ga ulaysiz.

📖 Javob

Sabab: token yo'q yoki URL qoidasiga ko'ra ruxsat yo'q bo'lsa, so'rov filter chain'da to'xtaydi — DispatcherServlet'gacha, demak controller advice'gacha, yetmaydi. Default'da klient bo'sh tanali 401 yoki HTML sahifa oladi.

@Bean
SecurityFilterChain api(HttpSecurity http, ObjectMapper json) throws Exception {
    http
        .authorizeHttpRequests(a -> a.anyRequest().authenticated())
        .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
        .exceptionHandling(e -> e
            .authenticationEntryPoint((req, res, ex) ->
                write(res, json, HttpStatus.UNAUTHORIZED, "Avtorizatsiyadan o'tilmagan"))
            .accessDeniedHandler((req, res, ex) ->
                write(res, json, HttpStatus.FORBIDDEN, "Bu amal uchun huquq yetarli emas")));
    return http.build();
}

private static void write(HttpServletResponse res, ObjectMapper json,
                          HttpStatus status, String detail) throws IOException {
    ProblemDetail body = ProblemDetail.forStatusAndDetail(status, detail);
    res.setStatus(status.value());
    res.setContentType(MediaType.APPLICATION_PROBLEM_JSON_VALUE);
    json.writeValue(res.getOutputStream(), body);
}

Nozik joylar:

  • resource server bilan — oauth2ResourceServer o'zining entry point'ini o'rnatadi (WWW-Authenticate header bilan). Uni almashtirmoqchi bo'lsangiz, o.authenticationEntryPoint(...) ichida ham bering;
  • @PreAuthorize xatolari — bu AccessDeniedException controller qatlamida chiqadi. Agar advice'da @ExceptionHandler(Exception.class) bo'lsa, u exception'ni yutib, 500 qaytaradi. Yo AccessDeniedException'ni advice'da alohida ushlang, yo qayta tashlang;
  • javob formati — API'ning boshqa xatolari bilan bir xil ProblemDetail bo'lsa, frontend uchun bitta xato ishlovchi yetadi;
  • xabarda sababni oshkor qilmang ("token muddati tugagan" yetarli, "imzo kaliti mos emas" emas).

Tekshirish: curl -i bilan token'siz va noto'g'ri rol bilan chaqirib, status, Content-Type va tanani ko'ring; buni @WebMvcTest testi bilan mustahkamlab qo'ying.