spring-projects / spring-projects/spring-security

Add @AuthorizeRequestMapping annotation

Open
#16,250 7 comments 0 reactions 1 assignee View on GitHub

@rwinch is already working on this.

Since Dec 9, 2024.

in: web type: enhancement
Dominant language
Java
Stars
9.6k
Forks
6.3k
Avg merge
2d 11h
Merged PRs (30d)
52

Description

Combined with gh-16249 we could add an annotation (e.g. @AuthorizeRequestMapping) that allows adding authorization rules to Spring Controllers but happens at the same time as authorizeHttpRequests() (to reduce the attack surface) rather than late like method security.

The need for a new annotation is due to the fact that @PreAuthorize allows access to method parameters, but we will not have access to those parameters in a web based authorization model.

We'd need the ability to scan for all annotated controllers and create a mapping of the RequestMapping to authorization rules.

A few examples:

@GetMapping("/users/{id}")
@AuthorizeRequestMapping("hasRole('ADMIN')")
User findById(String id) {

}
@GetMapping("/users/{id}")
@AuthorizeRequestMapping("@authz.canReadUser(authentication, #id)")
User findById(String id) {
  // authz is a bean name
  // canReadUser is a method on the authz bean that returns a boolean and accepts a String that is the id of the user to check
  // authentication is the current Authentication (same as all SpEL based Security)
  // id is the parsed id from the @GetMapping
}

The following adds an authorization rule that only admin can access the routes of /admin/users/{id} and /admin/users/.

@AuthorizeRequestMapping("hasRole('ADMIN')")
class AdminController {

  @GetMapping("/admin/users/{id}")
  User findUserById(String id) {

  }

  @GetMapping("/admin/users/")
  List<User> users() {

  }

}

We also need the ability to take into account all of the information that a Spring Controller would take into account (e.g. HTTP Method, Content negotiation, etc).

cc @rstoyanchev

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.