@RestController
@PreAuthorize("hasRole('TEACHER')") //annotating the controller class with PreAuthorize will provide "default" required acccess for all of the controller's methods
public class StudiesController {
@PreAuthorize("hasAnyRole('STUDENT', 'TEACHER')") //both students AND teachers have to to be able to access the study schedule. hence, we override the "default" required access to also allow students to access this method
@GetMapping("/schedule")
public Map<String, String> getSchedule() {
//some code
}
@GetMapping("/grades/{studentId}")
public Map<String, Integer> getGradesOfStudent(@PathVariable Integer studentId) { //only teachers have to be able to access a student's grades, so we do not override the "default" access level
//some code
}
}
1条答案
按热度按时间igsr9ssn1#
正如@dur所建议的,没有一种方法可以“扩展”Controller方法的授权角色(至少我不知道)。不过,有一种很好的方法可以实现您想要的功能。假设您有一个名为
StudiesController
的控制器:基本上,默认情况下,每个方法都只能由教师访问。任何你想让其他角色访问的方法,你可以用
@PreAuthorize
注解,并使用hasAnyRole
方法列出允许的角色。不过,这确实导致你必须为这样的方法编写'TEACHER'
。另外,不要忘记将
@EnableMethodSecurity
添加到SecurityConfig
类中以启用@PreAuthorize
注解