2.springsecurity-authorization

2.springsecurity-authorization

table of Contents:

1. Authorization concept

The so-called authorization is that if a user wants to access a certain resource, we have to check whether the user has such a permission, if it has the permission, it will be allowed to access it, and if it does not have it, it will not be allowed.

2. Case

This case is relatively simple, not obtained from the database, focusing on authorization-related content!

1. First prepare the users needed for the test

 @Override //配置用户相关
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication() //基于内存的认证
        .withUser("王泽").password("123456").roles("user").and()
                .withUser("wangze").password("123456").roles("admin");

    }

Since Spring Security supports multiple data sources, such as memory, database, LDAP, etc., these different sources of data are collectively encapsulated into a UserDetailService interface, and any object that implements this interface can be used as an authentication data source.

Therefore, we can also provide an instance of UserDetailService by overriding the userDetailsService method in WebSecurityConfigurerAdapter to configure multiple users:

@Bean
protected UserDetailsService userDetailsService() {
    InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
    manager.createUser(User.withUsername("wangze").password("123456").roles("admin").build());
    manager.createUser(User.withUsername("王泽").password("123456").roles("user").build());
    return manager;
}

You can choose one of two methods for defining users based on memory.

2. Prepare the test interface

@RestController
public class IndexController {
    @GetMapping("/hello")
    public String hello(){
        return "hello security!!";
    }

    @GetMapping("/admin/hello")
    public String admin(){
        return "hello admin!!";
    }

    @GetMapping("/user/hello")
    public String user(){
        return "hello user!!";
    }

}

  • /hello: Just log in to access
  • /admin/hello: Can be accessed by admin
  • /user/hello: can visit with user identity
  • All resources that user can access, admin can access

3. Configure permission interception rules

 http.authorizeRequests() //开启配置
        .antMatchers("/admin/**").hasRole("admin")//具备某个角色
        .antMatchers("/user/**").hasAnyRole("admin","user")
        .anyRequest().authenticated() //除了上述两个只要登录就能访问

For the matching rules here, we use Ant-style path matching symbols. Ant-style path matching symbols are widely used in the Spring family, and its matching rules are also very simple:

Wildcardmeaning
**Matching multi-level paths
*Match one-level path
?Match any single character

The meaning of the above configuration is:

  1. If the request satisfies the path /admin/**format, the user needs to have admin role.
  2. If the request satisfies the path /user/**format, the user needs to have the user role.
  3. The remaining request paths in other formats can be accessed only after authentication (login).

Note that the order of the three rules configured in the code is very important. Similar to Shiro, Spring Security also matches in the order from top to bottom when matching. Once it is matched, it will not continue to match, so the order of interception rules cannot be written wrong. .

4. Test

Since our configuration is:

.antMatchers("/user/**").hasAnyRole("admin","user")

So admin can also access user, so what if we want to realize that admin can access user automatically? ? Here is the role inheritance!

3. Role inheritance

To implement all the resources that the user can access, the admin can access it. This involves another knowledge point called role inheritance.

The upper level may have all the permissions of the lower level. If role inheritance is used, this function is very easy to implement. We only need to add the following code in SecurityConfig to configure the role inheritance relationship:

@Bean
RoleHierarchy roleHierarchy() {
    RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
    hierarchy.setHierarchy("ROLE_admin > ROLE_user");
    return hierarchy;
}

Note that in the configuration, you need to manually add character ROLE_prefix. The above configuration means ROLE_adminautomatically have ROLE_userpermission.

After configuration is complete, restart the project, this time we found wangze can also access /user/hellothis interface up.