SpringSecurity principle analysis and system design authority

Spring Secutity and Apache Shiro are the two main areas of open source security framework for Java, the main technology selection is permissions system design. This paper describes the implementation principle Spring Secutity and Spring Secutity design is based on RBAC permissions-based system.

First, the technology selection

Why the Spring Secutity rights as technology selection system, the main consideration several of the following aspects:

  1. Capacity data authentication : Spring Secutity support data authentication, that is fine-grained access control.
  2. Ecological basis Spring : Spring and Spring Secutity can seamlessly integrate ecology.
  3. Diverse authentication capabilities : Spring Secutity support multiple authentication methods, such as pre-authentication can be integrated with third-party authentication system.
Spring Security Apache Shiro
Authenticate Support for multiple authentication methods (such as passwords, anonymous, pre-certification ) Simple login authentication
Authentication Authentication function, data authentication Authentication function
Multi-source adaptation Mem、JDBC、DAO、LDAP、
OpenID、OAuth等
LDAP、JDBC、Kerberos、
ActiveDirectory等
encryption It supports a variety of encryption Simple encryption
Operating Environment Dependence Spring Can be run independently
Openness Open Source, Spring ecological basis Open source
the complexity Complex, heavy Simple, flexible

Second, the core architecture

Permission system generally contains two core modules: authentication (Authentication) and authentication (Authorization).

  • Certification : Certification module is responsible for the legality authenticate users, authentication token is generated and saved to the server session (such as TLS).
  • Authentication : user authentication module is responsible for obtaining identity information from the server session, permissions and access to resources than.

Spring Security's core architecture diagram official gives the following:

Core Architecture Interpretation:

  • The AuthenticationManager : responsible for authentication management, resolve user login information (encapsulated in Authentication), read users, roles, permissions, authentication information, the authentication result is backfilled to Authentication, save in SecurityContext.
  • The AccessDecisionManager : results of voting in charge of authentication, summary voter, one vote achieved by (the default), through votes, a veto strategy.
  • SecurityInterceptor : responsible authority to intercept, including the Web URL method call interception and interception. Access to resources through ConfigAttributes description information, by means of AccessDecisionManager authenticate interception.
  • SecurityContext : security context, save the authentication result. Provides a global context, thread inherits the context, independent thread context (default) three strategies.
  • Authentication : authentication information, saving the user's identity mark, the list of permissions, certificates, authentication information markings.
  • SecuredResource : the security management and control of resources, such as Web URL, users, roles, custom fields and other objects.
  • ConfigAttributes : Dev configuration, resource description information security control is provided for the logic input intercept SecurityInterceptor.

Third, the design principle

Through the analysis of the source code, I put the core domain model Spring Security design are summarized as follows:

Global abstract model interpretation:

  • Configuration : Global AuthenticationConfiguration responsible for the accreditation system, GlobalMethodSecurityConfiguration responsible for intercepting method calls the global configuration.
  • Building : AuthenticationConfiguration build authentication manager AuthenticationManager by AuthenticationManagerBuilder, GlobalMethodSecurityConfiguration AbstractSecurityInterceptor automatically initialize method call interception.
  • Web interception : HttpSecurity of Web security configuration, built a large number of GenericFilterBean URL filter to intercept. Responsible for the accreditation of the filter will be certified by AuthenticationManager, save the authentication result to SecurityContext.
  • Intercept method : Spring intercepts annotated method marked @ PreAuthorize, @ PreFilter, @ PostAuthorize , @ PostFilter such as by AOP technology (cglib / aspectj), authenticates the call AuthenticationManager by AbstractSecurityInterceptor (if necessary).
  • Certification : Certification Manager AuthenticationManager with built-in authenticators AuthenticationProvider, as long as a certification by the authentication will be successful. Different AuthenticationProvider access to information (HTTP requests, database queries, remote services, etc.) to authenticate their needs, certified the results of all packaged in Authentication. Need to load users, roles, permissions authenticator information (such as password authentication, pre-certification, etc.) need to butt UserDetailsManager user interface CRUD functionality.
  • Authentication : Permissions interceptor AbstractSecurityInterceptor SecurityMetadataSource by reading different loading needs to be described ConfigAttribute authentication information resource, then the Authentication authentication information, resource description ConfigAttribute, resource object itself is transmitted to the vote AccessDecisionManager. AccessDecisionManager built plurality of voter AccessDecisionVoter, ConfigAttribute converter will voter authentication information is a format SpringEL, logical expressions based authentication, authentication logic forwards by reflection by way of the expression processor to perform SecurityExpressionHandler SecurityExpressionRoot respective operations of up.
  • Custom : can be customized by WebSecurityConfigureAdapter HTTP security configuration HttpSecurity and authentication manager generator AuthenticationManagerBuilder; can customize the authentication filter through the AbstractPreAuthenticatedProcessingFilter; by UserDetailsManager and UserDetails interfaces may interface custom data sources; information GrantedAuthority customization privileges; can be tailored from by PermissionEvaluator access control logic defined in the domain model.

Fourth, application integration

After clarifying custom points of Spring Security, Spring Security can be integrated within the system.

Way to use pre-certified here to fit third-party certification system. Providing a pre-authentication AbstractPreAuthenticatedProcessingFilter extension point, a custom filter authentication Based on the abstract class.

public class MyPreAuthFilter extends AbstractPreAuthenticatedProcessingFilter {
    @Override
    protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
        // 从第三方系统获取用户ID
        return userId;
    }

    @Override
    protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
        return "";
    }
}

Spring Security information based on the user ID authentication filter getPreAuthenticatedPrincipal returned load the initial information of the user roles. It should be realized UserDetailsManager interface, providing the user information manager.

@Service
public class MyUserManager implements UserDetailsManager {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库加载用户信息
        return user;
    }
    
    // 其他管理接口
}

UserDetails contained within GrantedAuthority abstract interface type of permission information, it can generally be based on custom roles and permissions. Spring Security uses a form of expression Interface roles and permissions, roles and permissions difference is the role of ID is "ROLE_" as a prefix.

public class MyRole implements GrantedAuthority {
    private final String role;

    @Override
    public String getAuthority() {
        return "ROLE_" + role;
    }
}

public class MyAuthority implements GrantedAuthority {
    private final String authority;

    @Override
    public String getAuthority() {
        return authority;
    }
}

Then register the custom filters and user authentication manager, where the need to implement WebSecurityConfigurerAdapter for Web security configuration.

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, mode = AdviceMode.PROXY)
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsManager userDetailsManager;

    @Bean
    protected AuthenticationProvider createPreAuthProvider() {
        // 注册用户管理器
        PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
        provider.setPreAuthenticatedUserDetailsService(new UserDetailsByNameServiceWrapper<>(userDetailsManager));
        return provider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 注册预认证过滤器
        http.addFilter(new MyPreAuthFilter(authenticationManager()));
    }
}

In this way, the most simple internal integration within the framework of Spring Security system has been completed. Service interface on any authentication system may be used in the following manner.

public interface MyService {
    @PreAuthorize("hasAuthority('QUERY')")
    Object getById(String id);
    
    @PreAuthorize("hasRole('ADMIN')")
    void deleteById(String id);
}

PreAuthorize annotation indicates that the call before authentication, Spring defaults to using technology to generate dynamic proxy authentication logic. Notes configuration within the SpringEL expressions to customize the authentication method. The above code, hasAuthority checks whether the user has permission to QUERY, checks whether the user has hasRole ADMIN role.

Using dynamic proxy AOP way, allowed only authority to intercept at the interface level, if you want permissions on any method interception, then you need to be by means of AspectJ AOP way. First annotation EnableGlobalMethodSecurity the mode is set to AdviceMode.ASPECTJ, and then add the JVM startup parameters, so you can use the Spring Security annotation on any method.

-javaagent:/path/to/org/aspectj/aspectjweaver/1.9.4/aspectjweaver-1.9.4.jar

Or just above the user's identity information (roles / permissions) permissions, limited flexibility, can not play to the ability of Spring Security's authentication data. To use data authentication, the need to achieve a Spring Bean.

@Component
public class MyPermissionEvaluator implements PermissionEvaluator {
    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        // 自定义数据鉴权
        return false;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        // 自定义数据鉴权
        return false;
    }
}

PermissionEvaluator is automatically registered Spring Security Framework, and allows the use of authentication in a manner that the annotation.

@PreAuthorize("hasPermission(#id, 'QUERY')")
Object func1(String id) {
}

@PreAuthorize("hasPermission(#id, 'TABLE', 'QUERY')")
Object func2(String id) {
}

Wherein, func1 annotations indicating whether to validate the user has permission QUERY id, code logic is routed to the first interface MyPermissionEvaluator. func2 annotations indicating whether to validate the user has permission TABLE QUERY type id, MyPermissionEvaluator code logic is routed to the second interface. PermissionEvaluator provides extension points grant system data authentication, will describe later how to use this extension point to customize RBAC permissions-based system.

Fifth, the privilege system

Construction of RBAC (Role Based Access Control) system based on permissions, users need to be clear, roles, permissions, resources these core concepts like the relationship between meaning and them.

  • Resource : within the limits of safety control systems need to object, usually the data or function within the system.
  • Permissions : abstract describes the operation of the resource, usually an action.
  • Authorization : a combination of authority and resources, represents an operation on a resource.
  • Role : Describes a collection of authorization, represent a special class feature set of concepts.
  • User : principal permission system, the general user is accessing the current system, the user can have multiple roles.

The following is based on the rights of our core areas RABC model design:

Under normal circumstances, the system needs to access control list is not user-defined resources, because resources will be coupled to a lot of business logic, so we provide the resources from the factory, the resources required to build the service module through the configuration of the way. And users, roles, permissions, and authorization records are updated can be queried by the appropriate manager.

In addition, resource abstraction allows the expression of inheritance and composition relations resources, which in turn express more complex resource model, the resource unified authentication process:

  • When performing authentication, first look at the resources or combination of resources is an atomic resource.
  • For the atomic resource, first check whether there are authorized to record, and then view the role of pre-authorization contains the current authorization, there is a will to succeed.
  • Atomic resources are not authorized to record and pre-authorization roles, try parent resource (if any) in place of the authentication, or authentication fails.
  • For the combination of resources, to expand resources, access to child resource list.
  • Walk the child list of resources, and in turn sub-resources for authentication, authorization after the child resource summarizes the results that the combined resources of the authentication result.

In summary, based on a uniform resource abstraction and resource allocation, construct, build a unified resource can be achieved, then unified authentication.

VI Summary Review

Starting from the architecture and principles of Spring Security, describes the open source security framework design ideas and details for authentication and authorization modules. And provides a method for integrating Spring Security within the system, combined with general RBAC permissions model system, we discuss the design and implementation of a Uniform Resource and build a unified authentication. If you need to design a new system of authority, Hope this helps.

Guess you like

Origin www.cnblogs.com/fanzhidongyzby/p/11610334.html