Shiro started to learn the Custom Realm implement authorization (V)

A custom Realm Authorization

  Premise: authentication, see Realm inheritance structure map interface as follows, in order to achieve authorization by custom Realm, just inherit and override the method to AuthorizingRealm

 

 Second, the implementation process

1, the new Module1, add the following dependent pom

<properties>
        <shiro.version>1.4.1</shiro.version>
        <loggingg.version>1.2</loggingg.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>${shiro.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>${loggingg.version}</version>
        </dependency>
    </dependencies>

2, the new class inherits UserRealm AuthorizingRealm, override method

public class UserRealm extends AuthorizingRealm {
    private UserService userService = new UserServiceImpl();
    private RoleService roleService = new RoleServiceImpl();
    private PermissionService permissionService = new PermissionServiceImpl();

    /**
     * 做认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = token.getPrincipal().toString();
        System.out.println("自定义Realm:" + username);
        User user = userService.queryUserByUserName(username);
        IF (User = null!) { 
            List < 
    // authorization methodString > Roles = roleService.queryRoleByUserName (username); 
            List < String > Permissions = permissionService.queryPermissionByUserName (username); 
            ActivityUser activityUser = new new ActivityUser (User, Roles, Permissions); 
            // Parameter 1: any object can be transferred | 2 parameters: user password database | 3 parameters: the current class name 
            SimpleAuthenticationInfo info = new new SimpleAuthenticationInfo (activityUser, user.getPwd (), this.getName ()); 
            return info; 
        } the else { 
            return null; 
        } 
    } 

    protected AuthorizationInfo doGetAuthorizationInfo (Principal PrincipalCollection ) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        System.out.println("doGetAuthorizationInfo被回调了");
        //
        Object primaryPrincipal = principal.getPrimaryPrincipal();
        System.out.println(primaryPrincipal);

        ActivityUser activityUser = (ActivityUser) principal.getPrimaryPrincipal();
        List<String> roles = activityUser.getRoles();
        if (roles != null && roles.size() > 0) {
            info.addRoles(roles);
        }
        List<String>= activityUser.getPermissins permissins (); 
        IF (! = null & permissinspermissins & .size ()> 0) 
        { 
            info.addStringPermissions (permissins); 
        } 
        // If the judgment is super administrator 
        //info.addStringPermission("*:* "); 
        return info; 
    }

3, test class Test Method

TestAuthorizationRealm class public 
{ 
    public static void main (String [] args) 
    { 
        //. 1 username and password transmitted analog reception. 
        String username = "zhangsan"; 
        String password = "123456"; 
        . 2 // Create a security manager factory 
        factory's < the securityManager > factory = new new IniSecurityManagerFactory ( "CLASSPATH: shiro.ini"); 
        .. 3 // Get the security manager by the security manager factory 
        DefaultSecurityManager securityManager = (DefaultSecurityManager) factory.getInstance (); 
        .. 4 // Create custom the Realm 
        UserRealm to UserRealm UserRealm to new new = (); 
        .. 5 // custom setting Realm 
        securityManager.setRealm (userRealm); 
        //. 6.The security manager is bound to the current operating environment
        SecurityUtils.setSecurityManager (securityManager); 
        .. 7 // Get the current environment body Subject 
        Subject subject1 SecurityUtils.getSubject = (); 
        .. 8 // login method calls body 
        the try 
        { 
            subject1.login (new new UsernamePasswordToken (username, password)) ; 
            System.out.println ( "successful login ~"); 

// = subject1.getPrincipal Principal Object (); 
// System.out.println (Principal); 

        } the catch (IncorrectCredentialsException E) { 
            System.out.println ( " password incorrect "); 
        } the catch (UnknownAccountException E) { 
            System.out.println (" user name does not exist "); 
        } 

        Boolean role1 = subject1.hasRole ("role1");
        boolean role2 = subject1.hasRole("role1");
        System.out.println(role1);

        boolean permitted = subject1.isPermitted("user:add");
        System.out.println(permitted);
    }
}

Third, analysis

1, when performing the authorization, the authorization will be once each time the callback method defined self doGetAuthorizationInfo Realm to verify the following:

① Print Log in internal authorization method

 

 ②test class 3 times authorized to view the console as follows:

 

2, authentication when to check the library, check the roles, permissions, and package objects, avoid calling repeatedly lead to frequent check authorization database performance degradation

 

 

 IV Summary

1, every time the authorization, the authorization method is called (can be verified by printing logs)

2, avoid the check in the authorization database callback method resulting in performance degradation

3, the authorization method parameters can be obtained first authentication method into any parameter (in the figure there is described, also be implemented by subject.getPrincipal () method on the parameters), so I use package, to achieve a plurality of times when you call authorization method is the same object, avoid frequent check library

 

Guess you like

Origin www.cnblogs.com/rmxd/p/11768605.html