Spring Security (15): Permission control based on the RBAC data model

The official Spring Security document introduces this: Spring Security is a powerful and highly customizable identity authentication and access control framework. We have spent more than a dozen pages on authentication and authorization, and another important feature of it is access control. In this article, we will talk about its content.

Access control

Confusing concepts

  • First of all, and 前端功能权限控制is not the same.
  • Front-end function permissions Which roles have which permissions are only controlled in terms of whether the page buttons are grayed out or whether to display some functions, and which functions are available in different roles.
  • And what we are explaining in this article is 后台接口的访问权限控制that there are different permission restrictions for different roles to access different interfaces at the back-end level.

The permission control involved in the previous article

For example

  • In fact, we have been exposed from the beginning, for example, which interfaces can be accessed without logging in (login interface, etc.). The configuration items in the main configuration file are as follows:
	.authorizeRequests()
		// 排除对 "/authentication/require" 和 "/meicloud-signIn.html" 等的身份验证
		.antMatchers("/authentication/require", securityProperties.getBrowser().getSignInPage(), "/code/*")
		.permitAll()
		// 表示所有请求
		.anyRequest()
		// 需要身份验证
		.authenticated()
		.and()

Permission expression

  • The above .permitAll()represents the permission expression, there are many permission expressions that can be used as follows
Permission expression Description
permitAll Indicates that all is allowed, always return true
denyAll Means to reject all, always return false
anonymous Returns true if the current user is anonymous
rememberMe Returns true if the current user is a rememberMe user
authenticated Returns true if the current user is not anonymous
fullyAuthenticated Returns true if the current user is neither anonymous nor rememberMe user
hasRole Returns true when the user has the specified permission
hasAnyRole ([role1, role2]) Returns true when used to have any role permissions
hasAuthority Returns true when the user has the specified permission
hasAnyAuthority([authority1, authority2]) Returns true when the user has any of the specified permissions
hasIpAddress(‘192.168.1.0/24’) Returns true when the requested Ip matches
  • You can see which permission expressions can be used in the code
    Optional permission expression

Authority control based on RBAC data model

  • Of course the above is only Spring Security提供的一些方便操作的权限控制表达式. In actual projects, there are various roles, and different roles have different permissions. How to design this time?

RBAC data model

  • Full name: Role-Based Access Control(role-based access control)
  • There are generally five tables 三张主体表(用户、角色、权限),两张关联表(用户-角色、角色-权限).
  • Diagram
    RBAC data model

Realize Spring Security's permission control based on RBAC data model

  • Define the RbacServiceinterface
public interface RbacService {
    
    
	boolean hasPermission(HttpServletRequest request, Authentication authentication);
}
  • Define its implementation class RbacServiceImpl, in fact, all the permissions of the current user are 在登录授权的时候设置进了authentication中.
@Component("rbacService")
public class RbacServiceImpl implements RbacService {
    
    

	private AntPathMatcher antPathMatcher = new AntPathMatcher();

	@Override
	public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
    
    
		Object principal = authentication.getPrincipal();
		boolean hasPermission = false;

		if (principal instanceof Admin) {
    
    
			// 如果用户名是admin,就永远返回true
			if (StringUtils.equals(((Admin) principal).getUsername(), "admin")) {
    
    
				hasPermission = true;
			} else {
    
    
				// 读取用户所拥有权限的所有URL
				Set<String> urls = ((Admin) principal).getUrls();
				for (String url : urls) {
    
    
					if (antPathMatcher.match(url, request.getRequestURI())) {
    
    
						hasPermission = true;
						break;
					}
				}
			}
		}
		return hasPermission;
	}
}
  • Apply into Spring Security, create a configuration class to implement the AuthorizeConfigProviderinterface
@Component
public class DemoAuthorizeConfigProvider implements AuthorizeConfigProvider {
    
    
	@Override
	public boolean config(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry config) {
    
    
		//demo项目授权配置
		return false;
	}
}
  • In fact, there are mainly two points. One thing to note is that the permissions of the login role need to be queried and set in Authentication when logging in. The other is to write about how to intercept access permissions matching different interfaces, and one more point is how to Configured into Spring Security, the current blogger uses a lower version to configure this way. The configuration of the advanced version should be much simpler. Using some annotations can meet our needs. If there is time, a company version may be published later. Control scheme and operation.

Guess you like

Origin blog.csdn.net/qq_36221788/article/details/106977555