Spring Security's permission scheme - user authorization

foreword

Earlier we explained about the processing of user authentication. What happens after user authentication is completed? Of course, it is for our subject to authorize, so how is authorization realized? After reading this article, you should have a general understanding.

hasAuthority

It means that the current subject has a specified permission, then return true, otherwise return false

hasAnyAuthority

Returns true if the current principal has any permissions (given as a comma-separated list of strings) provided.

hasRole

If the user has the given role then access will be granted, otherwise a 403 status code will appear.

Returns true if the current principal has the specified role.

hasAnyRole

It is used to indicate that the user can access any one of the conditions.

Annotation use

@Secured

Determine whether it has a role. Another thing to note is that the matched string here needs to be prefixed with "ROLE_".

To use annotations, you must first enable the annotation function!

@EnableGlobalMethodSecurity(securedEnabled=true)

@SpringBootApplication

@EnableGlobalMethodSecurity(securedEnabled=true)

public class DemosecurityApplication {

         public static void main(String[] args) { SpringApplication.run(DemosecurityApplication.class, args);

        }

}

Annotate the controller method

// test annotation

@RequestMapping("test_secured")

@ResponseBody

@Secured({"ROLE_normals","ROLE_admins"})

public String helloUser() {

         return "hello,user";

}

@PreAuthorize

First of all, we need to enable the use of annotations

@EnableGlobalMethodSecurity(prePostEnabled = true)

@PreAuthorize: This annotation is the permission verification before entering the method

@PreAuthorize: The roles/permissions parameters of the logged-in user can be passed into the method.

@RequestMapping("/preAuthorize")

@ResponseBody

@PreAuthorize("hasAnyAuthority('system:menu')")

public String preAuthorize(){

        System.out.println("preAuthorize");

         return "preAuthorize";

}

@PostAuthorize

First enable the annotation function:

@EnableGlobalMethodSecurity(prePostEnabled = true)

@PostAuthorize : The annotation is not used much, and the permission verification will be performed after the method execution is completed, which is suitable for verifying the permission with the return value.

@PreFilter

Filter the data before entering the controller

@PostFilter

After the permission verification, the data is filtered and the user name is the user data that we set in response

Well, let’s talk about user authorization first.

Welcome everyone to click on the card below to pay attention to "coder trainees"

おすすめ

転載: blog.csdn.net/ybb_ymm/article/details/130134950