Spring Security also provides a note-based approach to implementing method-based Authorization. This is the @RolesAllowed note presented in this article . @RolesAllowed are annotations defined by JSR250.
(1) in the Spring-security.xml files are enabled JSR250 annotation Support.
<!---<jsr250-annotations= "enabled"/ >
(2) in the method that requires authorization control, add @RolesAllowed Annotations.
@RolesAllowed annotations can support the parameter values of a string array, indicating that the current user has one of several roles that satisfies the condition of authorized access.
public classuserservice {@RolesAllowed ({"role_user", "role_admin"}) publicUserBean getuserbyname (String name) {UserBean user=NewUserBean (name,1001); System.out.println ("getuserbyname");returnuser;} @RolesAllowed ("role_admin") public voidaddUser () {System.out.println ("addUser");} @RolesAllowed ("role_admin") public voidremoveuser () {System.out.println ("removeuser");} @RolesAllowed ("role_admin") public voidupdateUser () {System.out.println ("updateUser");}}
(3) Call the relevant Method.
@Controller @requestmapping ("home") public classHomeController {PrivateUserService userservice; publicuserservice getuserservice () {returnuserservice;} @Resource public voidSetuserservice (userservice Userservice) { this. UserService =userservice;} @RequestMapping ("/") publicModelandview index () {modelandview MV=Newmodelandview (); Mv.addobject ("message", "hello,welcome!"); Mv.setviewname ("home/index"); UserBean User= this. Userservice.getuserbyname ("zhangsan"); this. Userservice.adduser (); this. Userservice.removeuser (); this. Userservice.updateuser ();returnmv;}}
(4) Test Run.
when using a Zhangsan users of the role_admin role Access These methods will allow access to all methods so that the page can be accessed normally.
Output result:
Getuserbyname
AddUser
Removeuser
UpdateUser
and when using a Wangwu users of the Role_user role access These methods will only allow access to the getuserbyname () query method, and will deny access to other additions and deletions to modify the method, The 403 page for which access is denied occurs .
Input Result:
Getuserbyname
Spring Security Application Development (20) method-based authorization (iv) using @rolesallowed annotations