编程知识 cdmana.com

Getting started with spring security (4)

According to the previous theory , We finished Token The chaos of , Verification of permission role , But when accessing the interface, I found , The current system cannot restrict access

How to verify permissions and roles ?

Spring Official documents 11.3.3. Method security expression By enabling permission role annotation

@PreAuthorize,@PreFilter,@PostAuthorize and @PostFilter

xml Startup and use

<global-method-security pre-post-annotations="enabled"/>

Annotations to enable :@EnableGlobalMethodSecurity(prePostEnabled = true)

How to restrict interface access ?

 /**
 *  Add users 
 *
 * @param user  User information 
 * @return
 */
@PreAuthorize("hasAnyRole('ADMIN')")
@PostMapping("save")
public R save(@NotNull User user) {
    userService.insert(user);
    return new R(HttpStatus.HTTP_OK, " Save user successful ");
}

@PreAuthorize("hasAnyRole('ADMIN')") Identify the current interface only ROLE_ADMIN Ability to visit .

How to get user information more easily

Inspired by the development framework used in the company's projects , Combined with our previous conjectures , It's not hard to understand how this needs to be done , Now that you've given permission to SpringSecurity, It must have been from SpringSecurity In order to get .

  • How to give permissions to SpringSecurity management ?
SecurityContextHolder.getContext().setAuthentication(Authentication authentication);

Conclusion

So far, we have completed the simple permission role verification of front end and back end separation , In the process of perfecting this code , I have an obvious feeling ,Spring The beauty and strength of the framework , It's hard for him to understand , It's hard to get started , It's hard to understand . But that's the beauty , Come on ! Sao Nian !

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[Shao Jie]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/08/20210809183600815I.html

Scroll to Top