Springboot integration ApachShiro complete the login authentication and rights management

1 Introduction

Make a system the biggest problem is the question of security and permissions, how to choose a proper security framework to protect their own systems, common frameworks in this area has SpringSecurity, but considering its size and complexity, most companies still select

ApachShiro this framework as the company's security framework, here we have this framework is particularly necessary, therefore, began to build!

2. Introduction What do shiro

  • Authenticate users
  • User access control, such as:
    • Determining whether the user is assigned a certain security role.
    • Determining whether a user is granted permissions to complete the operation
  • Session API can be arbitrarily used in an environment of a non-web or EJB containers
  • Response authentication, access control, or events Session lifecycle
  • One or more user data source security data may be combined into a composite user "view" (view)
  • Supports single sign-on (SSO) function
  • Support the provision of "Remember Me" service, access to user-related information without having to log on

3.shiro Features

  • Authentication (authentication): user identification, commonly referred to as user "login"
  • Authorization (authorization): access control. For example, if a user has permission to use an operation.
  • Session Management (session management): user-specific session management, even in a non-EJB or web application.
  • Cryptography (encryption): While using an encryption algorithm to encrypt the data source, to ensure ease of use.

 There are other features to support and strengthen the field of security concerns in these different environments. In particular the following support functions:


  • Web Support: Shiro support provided by web api, can easily secure web applications.
  • Cache: Cache is fast and safe operation, high efficiency an important means of Apache Shiro guarantee.
  • Concurrency: Apache Shiro supports concurrency features multi-threaded applications.
  • Test: support unit testing and integration testing, and ensure that the code is as safe as expected.
  • "Run As": This feature allows the user to assume the identity of another user (licensed premise in).
  • "Remember Me": record the user's identity across session, only need to log in only when absolutely necessary.

3.Architecture architecture

Apache Shiro design philosophy is to make simple security procedures intuitive and easy to implement, Shiro core reference design for most users safe mode of thinking - how someone (or something) in a program that interacts with the environment safely control.

Programming generally user-story-based, that is, you will often design a user interface or service api based on how (or should) software to interact with the user. For example, you might say, "If my application the user interaction is logged in, I'll show them you can click a button to view their account information. If you do not log on, I'll show you a registered button."

4.Shiro architecture consists of three main ideas

  • Subject: As we mentioned in the last chapter, as an example, is currently running user-specific 'View' (view) on the Subject essence, while the word "User" often implies a person, Subject can be a person, but may also be a third-party service, the daemon accounts, cron job or other - any current events and software interaction. Subject instance and (need) a SecurityManager binding, and when you interact with a Subject, these interactions are converted into actions under SecurityManager Subject specific interaction action.

  • SecurityManager: SecurityManager is Shiro core architecture, with interior safety components together constitute the security umbrella. However, once a program configured the SecurityManager and its internal objects, SecurityManager usually be left alone, all the time developers spend almost all concentrated in the Subjet API. SecurityManager we will discuss in detail later, but it is important to know when you interact with a Subject. Subject to any security operation in SecurityManager is behind the real weight lifters, which can be reflected in the above chart.

  • Realms: Reamls is between Shiro and your data security program "bridge" or "connected", which is used and the actual safety-related data such as the user performs authentication (login) account number and authorization (access control) interact, Realm shiro configured from one or more programs to find these things. Realm is essentially on a specific security  the DAO : details of its source connected to the data package to obtain the relevant data needed to Shiro. When configuring Shiro, you must specify at least one Realm to implement authentication (authentication) and / or authorization (authorization). SecurityManager can configure multiple complex Realm, but at least one is needed. Shiro provide Realms out of the box to connect to a secure data source (or called address) such as LDAP, JDBC, such as INI file configuration and property files, etc., if the existing Realm can not meet your needs, you can also develop your own Realm achieve . And other internal components, like, Shiro SecurityManager management how to use the security and identity information to obtain Realms Subject instance represents.

5. Having said that understanding some of the concepts began to build

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>


        <!-- thymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!-- apache shiro -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- spring jpa -->    
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

6. Configuration ShiroConfig (note that the leader packet, is easy in the wrong direction)

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

@Configuration
public class ShiroConfig {
    
    /***
     * Configuration shiro filter factory Bean 
     * @author MRC 
     * @date 2019 Nian 6 morning of May 6 11:42:46 
     * @param securityManager 
     * @return 
     * / 
    @Bean 
    public ShiroFilterFactoryBean shirFilter (the SecurityManager securityManager) { 
        System.out.println ( "ShiroConfiguration.shirFilter ()" ); 
        ShiroFilterFactoryBean shiroFilterFactoryBean = new new ShiroFilterFactoryBean (); 
        shiroFilterFactoryBean.setSecurityManager (securityManager); 
        // interceptor. 
        the Map <String, String> = filterChainDefinitionMap new new a LinkedHashMap <String, String>();
         // configuration will not be blocked link order determination 
        filterChainDefinitionMap.put ( "/ static / **", "anon" );
         // disposed exit filter, wherein the specific exit code Shiro has been achieved for us 
        filterChainDefinitionMap.put ( "/ Zimbabwe Logout", "Zimbabwe Logout" );
         // <-! chain is defined by filtration, performed sequentially from top to bottom, generally / ** in the most lower ->: this is a pit it, believe it not so that the code;
         // <- authc:! All url must be certified before they can access through; anon: All url can have anonymous access -> 
        filterChainDefinitionMap.put ( "/ **", "authc" );
         // If you do not set a default will automatically find "/login.jsp" page under the Web project root 
        shiroFilterFactoryBean.setLoginUrl ( "/ the Login" );
        // After a successful login to jump link 
        shiroFilterFactoryBean.setSuccessUrl ( "/ index" );

        // unauthorized interface; 
        shiroFilterFactoryBean.setUnauthorizedUrl ( "/ 403" ); 
        shiroFilterFactoryBean.setFilterChainDefinitionMap (filterChainDefinitionMap); 
        return shiroFilterFactoryBean; 
    } 

    / ** 
     * tells the credential matching 
     * @return 
     * / 
    @Bean 
    public HashedCredentialsMatcher hashedCredentialsMatcher () { 
        HashedCredentialsMatcher hashedCredentialsMatcher = new new HashedCredentialsMatcher (); 
        hashedCredentialsMatcher.setHashAlgorithmName ( "MD5"); // hashing algorithm: MD5 algorithm used here; 
        hashedCredentialsMatcher.setHashIterations (2);// number of hash, such as the two hash corresponds to MD5 (MD5 ( "")); 
        return hashedCredentialsMatcher; 
    } 
    
    / ** 
     * ---- custom bridge "for which the actual safety-related data such as the user performs authentication (login) account number and authorization (access control) interacts 
     * @author MRC 
     * @date 2019 Nian 6 morning of May 6 11:44:45 
     * @return 
     * / 
    @Bean 
    public MyShiroRealm myShiroRealm () { 
        MyShiroRealm myShiroRealm = new new myShiroRealm ();
         // set password credentials matcher 
        myShiroRealm.setCredentialsMatcher (hashedCredentialsMatcher ());
         return myShiroRealm; 
    } 
    
    / ** * 
     * is the core of the SecurityManager Shiro architecture, with the internal security component composed safety umbrella
     @Author MRC * 
     * @date 2019 Nian 6 morning of May 6 11:46:23 
     * @return 
     * / 
    @Bean 
    public the SecurityManager securityManager () { 
        DefaultWebSecurityManager securityManager = new new DefaultWebSecurityManager (); 
        securityManager.setRealm (myShiroRealm ()); 
        return securityManager; 
    } 

    / ** 
     * open shiro aop supports proxy mode annotation; so the code needed to support open; 
     * 
     * @param securityManager 
     * @return 
     * / 
    @Bean 
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor (the securityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
    
    
    @Bean(name = "simpleMappingExceptionResolver")
    public SimpleMappingExceptionResolver createSimpleMappingExceptionResolver() {
        SimpleMappingExceptionResolver r = new SimpleMappingExceptionResolver();
        Properties mappings = new Properties();
        mappings.setProperty("DatabaseException", "databaseError");// 数据库异常处理
        mappings.setProperty("UnauthorizedException", "403");
        r.setExceptionMappings(mappings); // None by default
        r.setDefaultErrorView("error"); // No default
        r.setExceptionAttribute("ex"); // Default is "exception"
        // r.setWarnLogCategory("example.MvcLogger"); // No default
        return r;
    }
}
View Code

7. Configure Realms (arranged authentication and authorization)

It is used and the actual safety-related data such as the user performs authentication (login) account number and authorization (access control) interact, Realm Shiro configured from one or more programs to find these things. Realm is essentially on a specific security  the DAO : details of its source connected to the data package to obtain the relevant data needed to Shiro. When configuring Shiro, you must specify at least one Realm to implement authentication (authentication) and / or authorization (authorization)

public  class MyShiroRealm the extends AuthorizingRealm { 

    
    @Autowired 
    Private UserInfoService userInfoService; 
    
    / ** * 
     * When access to the page when the link is configured with the appropriate permissions or Shiro label will perform this method will not execute 
     * / 
    @Override 
    protected AuthorizationInfo doGetAuthorizationInfo ( Principals PrincipalCollection) { 
        System.out.println ( "rights profile -> MyShiroRealm.doGetAuthorizationInfo ()" ); 
        SimpleAuthorizationInfo authorizationInfo = new new SimpleAuthorizationInfo (); 
        
        the UserInfo the userInfo   = (the UserInfo) principals.getPrimaryPrincipal ();
         for(SysRole Role: userInfo.getRoleList ()) {
             // added role 
            authorizationInfo.addRole (role.getRole ());
             for (SysPermission the p-: role.getPermissions ()) {
                 // loop into the right information 
                authorizationInfo.addStringPermission (p .getPermission ()); 
            } 
        } 
        return authorizationInfo; 
    } 

    / ** * 
     * rewriting method of obtaining user information 
     * / 
    @Override 
    protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken token) throws of AuthenticationException { 

        System.out.println ("MyShiroRealm.doGetAuthenticationInfo ()" );
         // Get the user enters the account number. 
        String username = (String) token.getPrincipal (); 
        System.out.println (token.getCredentials ()); 
        // by username from the database find a User object, if found, could not find.
         // actual project, where you can do a cache according to the actual situation, if not, Shiro himself is also a time interval mechanism, will not repeat this method two minutes 
        UserInfo userInfo = userInfoService. findByUsername (username); 
        System.out.println ( "the userInfo ----- >> =" + the userInfo);
         IF (the userInfo == null ) {
             return  null ; 
        } 
        SimpleAuthenticationInfo authenticationInfo= new SimpleAuthenticationInfo(userInfo, // 用户名
                userInfo.getPassword(), // 密码
                ByteSource.Util.bytes(userInfo.getCredentialsSalt()), // salt=username+salt
                getName() // realm name
        );
        return authenticationInfo;

    }

}

8 specific comments in the code are written inside, import sql file out of the box Demo

Cloud code: https://gitee.com/mrc1999/Springboot-apachShiro

Reference: https://www.cnblogs.com/ityouknow/p/7089177.html

Reference: ApachShiro Chinese Reference Manual

 

Guess you like

Origin www.cnblogs.com/ChromeT/p/10984228.html