Spring Boot - определенная конечная точка в контроллере выдает 401 несанкционированную ошибку, а другие в том же контролJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Spring Boot - определенная конечная точка в контроллере выдает 401 несанкционированную ошибку, а другие в том же контрол

Сообщение Anonymous »

Код: Выделить всё

package com.hexa.amazecare.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.hexa.amazecare.dto.DoctorDTO;
import com.hexa.amazecare.service.DoctorService;

@RestController
@RequestMapping("/api/doctors")
public class DoctorController {

@Autowired
private DoctorService doctorService;

// Get doctor by ID
@GetMapping("/get/{id}")
public ResponseEntity getDoctorById(@PathVariable Long id) {
DoctorDTO doctorDTO = doctorService.getDoctorById(id);
return ResponseEntity.ok(doctorDTO);
}

//get doctors by Specialty
@GetMapping("/get-specialty/{speciality}")
public ResponseEntity getDoctorBySpecality(@PathVariable String specialty) {
List doctors = doctorService.getDoctorBySpecality(specialty);
return ResponseEntity.ok(doctors);
}

// Endpoint to get all doctors
@GetMapping("/get")
public ResponseEntity getAllDoctors() {
List doctors = doctorService.getAllDoctors();
return ResponseEntity.ok(doctors);
}

// Create a new doctor
@PostMapping("/add")
public ResponseEntity createDoctor(@RequestBody DoctorDTO doctorDTO) {
DoctorDTO newDoctor = doctorService.createDoctor(doctorDTO);
return ResponseEntity.ok(newDoctor);
}

// Update an existing doctor
@PutMapping("update/{id}")
public ResponseEntity updateDoctor(@PathVariable Long id, @RequestBody DoctorDTO doctorDTO) {
DoctorDTO updatedDoctor = doctorService.updateDoctor(id, doctorDTO);
return ResponseEntity.ok(updatedDoctor);
}

// Delete a doctor by ID
@DeleteMapping("delete/{id}")
public ResponseEntity deleteDoctor(@PathVariable Long id) {
doctorService.deleteDoctor(id);
return ResponseEntity.noContent().build();
}

// Endpoint to retrieve all specialties
@GetMapping("/specialties")
public ResponseEntity getAllSpecialties() {
List specialties = doctorService.getAllSpecialties();
return ResponseEntity.ok(specialties);
}
}

Итак, у меня есть эти конечные точки в классе контроллера врача, хотя все конечные точки после авторизации работают отлично, конечная точка «getDoctorBySpecality» не дает соответствующего результата. Выдает ошибку 401 несанкционированного доступа.
Вот моя конфигурация безопасности для дальнейшего контекста:

Код: Выделить всё

    @Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

return http.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll() // Allow access to registration and login
.requestMatchers("api/patients/get/**").hasAnyRole("DOCTOR","PATIENT","ADMIN")
.requestMatchers("/api/patients/**").hasAnyRole("PATIENT","DOCTOR","ADMIN")
.requestMatchers("/api/doctors/get-specialty/").hasAnyRole("DOCTOR","PATIENT","ADMIN")
.requestMatchers("/api/doctors/**").hasAnyRole("DOCTOR","PATIENT","ADMIN")
.anyRequest().authenticated() // All other requests require authentication
)
.cors(Customizer.withDefaults())
.httpBasic(Customizer.withDefaults())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}

Не могли бы вы мне помочь?
Я попытался получить доступ к своей конечной точке через почтальона и получил ошибку 401 несанкционированного доступа. Я новичок в Springboot, поэтому не знаю, где я ошибаюсь.

Подробнее здесь: https://stackoverflow.com/questions/790 ... ed-error-w
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»