Spring Security provides a lot of permission control by default, but a good framework must be extensible, and Spring Security is very extensible. You can use the way Spring Security provides for authorization, You can also customize the authorization logic. In short, you can play it any way you want!

Today, Songo takes a look at four common permission controls in Spring Security.

  • Expression controls URL path permissions
  • Expression control method permissions
  • Use filter annotations
  • Dynamic permissions

Four ways. Let’s look at them separately.

This is the 30th article in the Spring Security series, and reading the previous articles will help you understand it better:

  1. Dig a big hole and Spring Security will do it!
  2. How to decrypt the password
  3. A step-by-step guide to customizing form logins in Spring Security
  4. Spring Security does front and back separation, so don’t do page jumps! All JSON interactions
  5. Authorization in Spring Security used to be so simple
  6. How does Spring Security store user data into the database?
  7. Spring Security+Spring Data Jpa, Security management is only easier!
  8. Spring Boot + Spring Security enables automatic login
  9. Spring Boot automatic login. How to control security risks?
  10. How is Spring Security better than Shiro in microservices projects?
  11. Two ways for SpringSecurity to customize authentication logic (advanced play)
  12. How can I quickly view information such as the IP address of the login user in Spring Security?
  13. Spring Security automatically kicks out the previous login user.
  14. How can I kick out a user who has logged in to Spring Boot + Vue?
  15. Spring Security comes with a firewall! You have no idea how secure your system is!
  16. What is a session fixed attack? How do I defend against session fixation attacks in Spring Boot?
  17. How does Spring Security handle session sharing in a clustered deployment?
  18. Songgo hand in hand to teach you in SpringBoot CSRF attack! So easy!
  19. Learn to learn thoroughly! Spring Security CSRF defense source code parsing
  20. Two poses for password encryption in Spring Boot!
  21. How to learn Spring Security? Why must we study systematically?
  22. Spring Security has two different resource release policies. Do not use them incorrectly.
  23. Spring Boot + CAS single sign-on
  24. Spring Boot is the third way to implement single sign-on!
  25. How do I Connect to the Database in Spring Boot+CAS SINGLE Sign-on?
  26. Spring Boot+CAS default login page is too ugly, how to do?
  27. How to carry Token in request header with Swagger
  28. Summary of three cross-domain scenarios in Spring Boot
  29. How to implement HTTP authentication in Spring Boot?

1. Expressions control URL path permissions

Let’s start with the first one, which is controlling URL path permissions through expressions, which Songo actually talked about in a previous article, so let’s go over it a little bit.

Spring Security supports the use of SpEL expressions for URL and method permission control. If the expression returns true, the corresponding permission is required; otherwise, the corresponding permission is not required. The class that provides the expression is SecurityExpressionRoot:

SecurityExpressionRoot has two implementation classes, representing the extension of SpEL to handle URL permission control and method permission control. For example, hasIpAddress is added to handle URl-path-based permission control.

Let’s take a look at the most basic spELS defined in the SecurityExpressionRoot class:

As you can see, these are all expressions for this class, and I’ll explain them a little bit:

expression note
hasRole A user has a role to access resources
hasAnyRole A user can access resources with any of multiple roles
hasAuthority Similar to hasRole
hasAnyAuthority Similar to hasAnyRole
permitAll All access
denyAll Deny all access
isAnonymous Check whether the user is anonymous
isAuthenticated Check whether the authentication is successful
isRememberMe Determine whether or not to remember what I logged in to
isFullyAuthenticated Check whether the user name or password is used to log in
principle The current user
authentication User object extracted from SecurityContext

That’s the basic, and in its inheritance class, there’s a little bit of extension, but I’m not going to go over that again.

If the permission is controlled by URL, you only need to configure it as follows:

protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/admin/**").hasRole("admin")
            .antMatchers("/user/**").hasAnyRole("admin"."user")
            .anyRequest().authenticated()
            .and()
            ...
}
Copy the code

The admin role is required to access the /admin/** path, and the admin or user role is required to access the /user/** path.

2. Expression control method permission

Of course, we can also control permissions by adding annotations to methods.

To add annotation control to a method, we first need to enable the use of annotations and add the following to the Spring Security configuration class:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {... . }Copy the code

This configuration enables three annotations, which are:

  • @preauthorize: Check the permissions of methods before executing them
  • @postauthorize: Verify permissions after methods are executed
  • @secured: Similar to @preauthorize

These three can be used in combination with SpEL in a very flexible way. Here are a few demos to share with you.

@Service
public class HelloService {
    @PreAuthorize("principal.username.equals('javaboy')")
    public String hello(a) {
        return "hello";
    }

    @PreAuthorize("hasRole('admin')")
    public String admin(a) {
        return "admin";
    }

    @Secured({"ROLE_user"})
    public String user(a) {
        return "user";
    }

    @PreAuthorize("#age>98")
    public String getAge(Integer age) {
        returnString.valueOf(age); }}Copy the code
  1. The first hello method, annotated with the constraint that only the user currently logged in with the name javaboy can access the method.
  2. The second admin method, which indicates that the user accessing this method must have the admin role.
  3. The user of this method must have the user role, but note that the user role needs to be addedROLE_Prefix.
  4. The fourth getAge method, which means that the age parameter to access the method must be greater than 98, or the request will not pass.

As you can see, the expression is still quite rich. If you want to refer to a method parameter, you can use a # to refer to either a primitive type parameter or an object parameter.

In addition to principal, the default object is authentication (see section 1).

3. Use filter annotations

Spring Security also has two filter functions, @prefilter and @postfilter, that automatically remove elements from a collection based on given conditions.

@PostFilter("filterObject.lastIndexOf('2')! = 1")
public List<String> getAllUser(a) {
    List<String> users = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        users.add("javaboy:" + i);
    }
    return users;
}
@PreFilter(filterTarget = "ages",value = "filterObject%2==0")
public void getAllAge(List<Integer> ages,List<String> users) {
    System.out.println("ages = " + ages);
    System.out.println("users = " + users);
}
Copy the code
  • In the getAllUser method, the collection is filtered and only elements with suffix 2 are returned, with filterObject representing the element object to be filtered.
  • In the getAllAge method, because there are two collections, the filter object is specified using filterTarget.

4. Dynamic permissions

Dynamic permissions are mainly achieved by rewriting interceptors and decision makers, which I have described in detail in the document of VHR. You can obtain documents by replying 888 in the background of the public account [Jiangnan Bit of Yu]. I will not repeat the details.

5. Summary

Well, today we have a little chat about authorization in Spring Security. Of course, there are a lot of details here, and Songko will talk about them in detail later.

If you feel that you have gained something, remember to click on songko under the encouragement of watching oh ~