Search code examples
javaspring-bootspring-restcontroller

How to send a 401 as unauthorized user and a 404 if a database query returned a null object in a Spring boot webapp REST API controller?


I'm using a bit of a personalized security back-end due to the nature of the app and was trying out how to implement a few simple error returns in my REST API controller. It's simple enough to do in a html page controller like I have in the following:

@Controller
public class HomeController {

    @Autowired
    private UserService userService;

    @GetMapping("/home.html")
    public String home(Model model) {
        String redirect = "home";

        if(!userService.getCurrentUser().isCanAccessService()) {
            redirect = "unauthorized";
        }       
        return redirect;
    }
}

I can easily just redirect it to the unauthorized page that I made since I'm returning the string value here. However, when I go to a REST API it's not as simple:

@RestController
public class bagelController {

    @Autowired
    private bagelService bagelService;

    @Autowired
    private UserService userService;

    @GetMapping("/rest/bagel/search")
    public Bagel searchBagel (@RequestParam(value = "bagel", required = false) String bagel, 
            @RequestParam(value = "bagelInd", required = false, defaultValue = "1") int bagelInd) {

        Bagel bagel;
        if(!userService.getCurrentUser().isBagelEditAccess()) {
            bagel = null;
            // I want to return a 401 or direct to my unathorized page if I get an invalid user here.
        }
        else {
            bagel = bagelService.getbagel(bagel, bagelInd);
            // if my bagel object returns null, I want to return a 404 or direct to a 404 not
               found page here.
        } 
        return bagel; 
    }

Solution

  • One way to do this.

        @GetMapping("/rest/bagel/search")
        public ResponseEntity<Bagel> searchBagel (@RequestParam(value = "bagel", required = false) String bagel, 
                @RequestParam(value = "bagelInd", required = false, defaultValue = "1") int bagelInd) {
    
            Bagel bagel = null;
            if(!userService.getCurrentUser().isBagelEditAccess()) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
            else {
                bagel = bagelService.getbagel(bagel, bagelInd);
                if(bagel == null) { 
                  return ResponseEntity.notFound().build();
                }
            } 
            return ResponseEntity.ok(bagel); 
        }