Woodchuck
Woodchuck

Reputation: 4414

Spring web app controller redirect based on results of another endpoint

I want to enforce some security in my Spring web app whereby a user can only access pages they are authorized for. If they don't have authorization, they should be redirected back to home.

For simplicity's sake, let's say the existing controllers are something straightforward like this:

...
@RestController
public class Page1Controller {
    
    @RequestMapping("/page1")
    public String index() {
        return "Welcome to Page 1!";
    }
}

There's also a REST endpoint that returns the pages the user can access. This is a nonstandard, legacy aspect of the code that I can't change. I'll omit the details for simplicity, but let's say that endpoint, /pageaccess/Bob, returns this json for user Bob, indicating he can access all pages except page2:

[
 {"page":page1, "text":"Function 1", "access":1},
 {"page":page2, "text":"Function 2", "access":0},
 {"page":page3, "text":"Function 3", "access":1},
 {"page":page4, "text":"Function 4", "access":1}
]

The app is coded so only pages the user has access to appear in the menu. The problem is they could still type in the url for a page they're not authorized to see (e.g., /page2) and see it anyway.

Can I add logic to the controllers (e.g., Page1Controller above) to call the pageaccess/{user} endpoint and then, based on those results, either return Page 2 or redirect back home (/)?

Upvotes: 0

Views: 171

Answers (1)

You must assume that clients will do exactly the sort of fiddling and exploring you mentioned. Therefore, you must handle security restrictions on the server. This is precisely what Spring Security is for; you would put something like the following on the relevant page:

@PreAuthorize("hasRole('PAGE_2_USER')")

Upvotes: 1

Related Questions