shiro framework for learning -4- Shiro built JdbcRealm

1. JdbcRealm database ready

JdbcRealm is the user's role, permissions are read from the database, which is used for user authentication and authorization security data sources to replace read from the database, there is no other difference, first create three tables in the database:

CREATE TABLE `users` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(100) DEFAULT NULL,
  `password` varchar(100) DEFAULT NULL,
  `password_salt` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `idx_users_username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
CREATE TABLE `user_roles` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(100) DEFAULT NULL,
  `role_name` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `idx_user_roles` (`username`,`role_name`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
CREATE TABLE `roles_permissions` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `role_name` varchar(100) DEFAULT NULL,
  `permission` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `idx_roles_permissions` (`role_name`,`permission`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

Insert data:

INSERT INTO `users` VALUES (1,'jack','123',NULL),(2,'xdclass','456',NULL);
INSERT INTO `roles_permissions` VALUES (4,'admin','video:*'),(3,'role1','video:buy'),(2,'role1','video:find'),(5,'role2','*'),(1,'root','*');
INSERT INTO `user_roles` VALUES (1,'jack','role1'),(2,'jack','role2'),(4,'xdclass','admin'),(3,'xdclass','root');

2. JdbcRealm profile

Note that the file format must be # ini, encoded as the ANSI 
# Realm declaration specifies the type of realm 
JDBCRealm = org.apache.shiro.realm.jdbc.JdbcRealm 

# source configuration data 
# com.mchange.v2.c3p0.ComboPooledDataSource the dataSource = 
the dataSource = COM .alibaba.druid.pool.DruidDataSource 

driving url # mysql-connector-java 5 using a com.mysql.jdbc.Driver, after mysql-connector-java6 with the com.mysql.cj.jdbc.Driver 
dataSource.driverClassName = com.mysql.cj.jdbc.Driver 

# avoid security warnings 
dataSource.url = jdbc: MySQL: // localhost:? 3306 / xdclass_shiro characterEncoding = UTF-8 & serverTimezone = UTC = false & useSSL 
dataSource.username = root 
dataSource.password = lchadmin 

# specified data source 
jdbcRealm.dataSource dataSource = $ 

# Find open permission, they will not automatically query permission roles corresponding to the actual cause has permission to call subject.isPermitted () returns false
= to true jdbcRealm.permissionsLookupEnabled

# Realms achieve the specified SecurityManager provided Realms, there may be multiple, separated by commas 
securityManager.realms = $ jdbcRealm

 

Test code

package net.xdclass.xdclassshiro;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Test;

/**
 * jdbcRealm操作
 */
public class{QuicksStratTest5_3 

    @Test 
    public  void testAuthentication () {
         // create a configuration file SecurityManager plant 
        Factory's <SecurityManager> Factory = new new IniSecurityManagerFactory ( "CLASSPATH: jdbcrealm.ini" );
        // Get instance SecurityManager 
        SecurityManager securityManager = factory.getInstance ();
         // set the current context 
        SecurityUtils.setSecurityManager (securityManager); 

        // get the current subject (application applied user) 
        the Subject Subject = SecurityUtils.getSubject ();
         // simulate user input 
        UsernamePasswordToken usernamePasswordToken =new new UsernamePasswordToken ( "Jack", "123" );
         //
         subject.login (usernamePasswordToken); 
        System.out.println ( "authentication result (if authorized):" + subject.isAuthenticated ());
         // final call is org.apache.shiro.authz.ModularRealmAuthorizer.hasRole method 
        System.out.println ( "is there role1 role:" + subject.hasRole ( "role1" )); 
        System.out.println ( "is there a role role2:" subject.hasRole + ( "role2" )); 
        System.out.println ( "Is there a root role:" + subject.hasRole ( "root" ));
         // get the login account 
        System.out.println ( "getPrincipal () : "+ subject.getPrincipal());
        //Verifies the role, no return value, the check is not passed, directly ran abnormal 
        subject.checkRole ( "role1" ); 
        System.out.println ( "======= subject.checkRole (\" role1 \ ") ===== passed " );
         // the User Jack has permission to find the video, performed by 
        subject.checkPermission (" video: find " );
         // are there video: find rights: to true 
        System.out.println (" are there are video: find authority: "+ subject.isPermitted (" video: find " ));
         //    Are there video: delete permissions: false 
        System.out.println (" Is there a video: delete permissions: "+ subject.isPermitted ( "video: the delete" ));
         // delete permissions user jack no video, the Executive will complain: org.apache.shiro.authz.UnauthorizedException:Subject does not have permission [video:delete]
        subject.checkPermission ( "Video: the Delete" ); 
        subject.logout (); 
        System.out.println ( "after logout authentication result:" + subject.isAuthenticated ()); 

       / * org.apache.shiro.realm.jdbc. JdbcRealm source 
       * 1. class JdbcRealm the extends AuthorizingRealm 
       * 2. preset default query, therefore create a consistent database field name to be defined and here! ! ! 
       Protected static String DEFAULT_AUTHENTICATION_QUERY Final * = "the SELECT password from the Users the WHERE username =?"; 
    Protected static String DEFAULT_SALTED_AUTHENTICATION_QUERY Final = "the SELECT password, password_salt from the Users the WHERE username =?"; # Roles based on user name search
    
    protected static Final String DEFAULT_USER_ROLES_QUERY = "the SELECT role_name from user_roles the WHERE username =?"; 
    * # user name search rights
    protected static Final String DEFAULT_PERMISSIONS_QUERY = "the SELECT permission from roles_permissions the WHERE role_name =?";
    protected String authenticationQuery = "the SELECT password from the Users username = the WHERE? ";
    protected String userRolesQuery =" role_name from the SELECT user_roles the WHERE username =? "; * # query based on the role permissions 
    protected String permissionsQuery =" roles_permissions the SELECT permission from the WHERE role_name = ";? 
    *
    * 3. protected boolean permissionsLookupEnabled = false; this switch is off by default, need to manually open 
    * 4.
     
    * protected AuthorizationInfo doGetAuthorizationInfo ( Principals PrincipalCollection) { 
        IF (Principals == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        } else {
            String username = (String)this.getAvailablePrincipal(principals);
            Connection conn = null;
            Set<String> roleNames = null;
            Set permissions = null;

            try {
                conn = this.dataSource.getConnection();
                roleNames = this.getRoleNamesForUser(conn, username);
                if (this.permissionsLookupEnabled) {
                    permissions = this.getPermissions(conn, username, roleNames);
                }
            } catch (SQLException var11) {
                String message = "There was a SQL error while authorizing user [" + username + "]";
                if (log.isErrorEnabled()) {
                    log.error(message, var11);
                }

                throw new AuthorizationException(message, var11);
            } finally {
                JdbcUtils.closeConnection(conn);
            }

            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
            info.setStringPermissions(permissions);
            return info;
        }
        * */
    }

    @Test
    public void test2(){
// 不使用配置文件的情况下: DefaultSecurityManager securityManager
= new DefaultSecurityManager(); DruidDataSource ds = new DruidDataSource(); ds.setDriverClassName("com.mysql.cj.jdbc.Driver"); ds.setUrl("jdbc:mysql://localhost:3306/xdclass_shiro?characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false"); ds.setUsername("root"); ds.setPassword("lchadmin"); JdbcRealm jdbcRealm = new JdbcRealm(); jdbcRealm.setPermissionsLookupEnabled(true); jdbcRealm.setDataSource(ds); securityManager.setRealm(jdbcRealm); will securityManager set to the current operating environment// SecurityUtils.setSecurityManager (securityManager); //Gets the current subject (application applied User) the Subject Subject = SecurityUtils.getSubject (); // simulate user input UsernamePasswordToken usernamePasswordToken = new new UsernamePasswordToken ( "Jack", "123" ); // subject.login (usernamePasswordToken); the System.out .println ( "authentication result (if authorized):" + subject.isAuthenticated ()); // final call is org.apache.shiro.authz.ModularRealmAuthorizer.hasRole method System.out.println ( "is there a role role1 : "+ subject.hasRole (" role1 " )); System.out.println ( " Is there role2 role: "+ subject.hasRole (" role2 " )); System.out.println("Is there a root role:" + subject.hasRole ( "root" )); // get the login account System.out.println ( "getPrincipal ():" + subject.getPrincipal ()); // checking role, no The return value, the check is not passed, directly thrown subject.checkRole ( "role1" ); System.out.println ( "======= subject.checkRole (\" role1 \ ") passed ==== = " ); // the User Jack has permission to find the video, performed by subject.checkPermission (" video: find " ); // are there video: find rights: to true System.out.println ( "Is there a video: find authority: "+ subject.isPermitted (" video: find ")); // are there video: delete permissions: false System.out.println ( "Is there a video: delete permissions:" + subject.isPermitted ( "video:delete")); // the User Jack not authorized to delete the video, will perform error: org.apache.shiro.authz.UnauthorizedException: Subject does not have have permission [video: the Delete] subject.checkPermission ( "video: the Delete" ); } }

 

Guess you like

Origin www.cnblogs.com/enjoyjava/p/12079743.html