Java源码示例:org.apache.shiro.util.Factory

示例1
private static SecurityManager createSecurityManager(Ini config, Supplier<String> sessionIdGenerator) {
    final Factory<SecurityManager> factory = new IniSecurityManagerFactory(config) {
        @Override
        protected SecurityManager createDefaultInstance() {
            final DefaultSessionManager sessionManager = new DefaultSessionManager();
            // This session DAO is required to cache the session in a very short time, especially while
            // logging in to the Central Dogma server. After that, the general session manager provided
            // by Central Dogma server will be working for the session management.
            sessionManager.setSessionDAO(new LimitedMemorySessionDAO(sessionIdGenerator,
                                                                     64, Duration.ofHours(1)));

            final DefaultSecurityManager securityManager = new DefaultSecurityManager();
            securityManager.setSessionManager(sessionManager);

            return securityManager;
        }
    };
    return factory.getInstance();
}
 
示例2
public static void main(String[] args) {
  //此处从ini文件来实现用用户角色权限配置,实际多从数据库表来实现
  Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini.bak");

  //SercurityManager 对象
  SecurityManager instance = factory.getInstance();
  SecurityUtils.setSecurityManager(instance);

  //测试用户
  Subject currentUser = SecurityUtils.getSubject();
  UsernamePasswordToken token = new UsernamePasswordToken("admin", "admin");

  boolean result = false;
  try {
    currentUser.login(token);
    result = true;
    LOG.debug("认证成功");
  } catch (Exception e) {
    result = false;
    LOG.debug("认证失败");
  }

}
 
示例3
@Test
public void helloWorld() {
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
    SecurityManager manager = factory.getInstance();
    SecurityUtils.setSecurityManager(manager);
    Subject subject = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken("admin", "admin");

    try {
        subject.login(token);
    } catch (AuthenticationException e) {
        LOG.error("Authentication Invalid: " + e.getMessage());
    }

    Assert.assertEquals(true, subject.isAuthenticated());

    subject.logout();
}
 
示例4
/**
 *
 * @param config - the shiro.ini config file created in topology deployment.
 * @return returns the Subject given by the shiro config's settings.
 */
protected Subject getSubject(Ini config) throws BadSubjectException {
  try {
    ThreadContext.unbindSubject();
    @SuppressWarnings("deprecation")
    Factory factory = new IniSecurityManagerFactory(config);
    org.apache.shiro.mgt.SecurityManager securityManager = (org.apache.shiro.mgt.SecurityManager) factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);
    Subject subject = SecurityUtils.getSubject();
    if( subject != null) {
      return subject;
    } else {
      out.println("Error Creating Subject from config at: " + config);
    }
  } catch (Exception e){
    out.println(e.toString());
  }
  throw new BadSubjectException("Subject could not be created with Shiro Config at " + config);
}
 
示例5
private static void setupShiro() {
    Ini ini = new Ini();
    Ini.Section usersSection = ini.addSection("users");

    usersSection.put(ALICE.email(), ALICE.roles());
    usersSection.put(BOB.email(), BOB.roles());
    usersSection.put(CAESAR.email(), CAESAR.roles());

    Ini.Section rolesSection = ini.addSection("roles");
    rolesSection.put(ROLE_A.label(), ROLE_A.permissions());
    rolesSection.put(ROLE_B.label(), ROLE_B.permissions());
    rolesSection.put(ROLE_C.label(), ROLE_C.permissions());
    rolesSection.put(ROLE_D.label(), ROLE_D.permissions());

    Factory<SecurityManager> factory = new TestIniSecurityManagerFactory(ini);
    SecurityManager secMgr = factory.getInstance();
    setSecurityManager(secMgr);
}
 
示例6
public static void login() throws Exception {
	Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
	org.apache.shiro.mgt.SecurityManager securityManager = (org.apache.shiro.mgt.SecurityManager) factory.getInstance();
	SecurityUtils.setSecurityManager(securityManager);
	Subject currentUser = SecurityUtils.getSubject();
	UsernamePasswordToken token = new UsernamePasswordToken(
			Constants.SYSTEM_BACKGROUND_USER, Constants.SYSTEM_BACKGROUND_PASSWORD);
	currentUser.login(token);
	//System.out.println(currentUser.hasRole("admin"));
	//System.out.println(currentUser.hasRole("*"));
}
 
示例7
@Override
public void contextInitialized(ServletContextEvent sce) {
  // Use the shiro.ini file at the root of the classpath
  // (file: and url: prefixes load from files and urls respectively):
  Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
  SecurityManager securityManager = factory.getInstance();

  // Since Vaadin doesn't really base its UI on distinct URL paths we will eschew
  // shiro web module entirely, we just don't need it.
  SecurityUtils.setSecurityManager(securityManager);

}
 
示例8
private static void setupShiro() {
    Ini ini = new Ini();
    Ini.Section usersSection = ini.addSection("users");
    usersSection.put(USER1, PASS1 + ",rolea,roled");
    usersSection.put(USER2, PASS2 + ",roleb,rolec");
    usersSection.put(USER3, PASS3 + ",rolec,rolee");
    Ini.Section rolesSection = ini.addSection("roles");
    rolesSection.put("rolea", "*");
    rolesSection.put("roleb", "permtype1:permaction1:perminst1");
    rolesSection.put("rolec", "permtype1:permaction2:*");
    rolesSection.put("roled", "permtype3:*");
    Factory<SecurityManager> factory = new TestIniSecurityManagerFactory(ini);
    SecurityManager secMgr = factory.getInstance();
    setSecurityManager(secMgr);
}
 
示例9
public static void main(String[] args) {
	log.info("My First Apache Shiro Application");

	Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro/shiro-app.ini");
	SecurityManager securityManager = factory.getInstance();
	SecurityUtils.setSecurityManager(securityManager);

	// get the currently executing user:
	Subject currentUser = SecurityUtils.getSubject();

	// Do some stuff with a Session (no need for a web or EJB container!!!)
	Session session = currentUser.getSession();
	session.setAttribute("someKey", "aValue");
	String value = (String) session.getAttribute("someKey");
	if ("aValue".equals(value)) {
		log.info("Retrieved the correct value! [" + value + "]");
	}

	// let's login the current user so we can check against roles and permissions:
	if (!currentUser.isAuthenticated()) {
		UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
		token.setRememberMe(true);
		try {
			currentUser.login(token);
		} catch (UnknownAccountException uae) {
			log.info("There is no user with username of " + token.getPrincipal());
		} catch (IncorrectCredentialsException ice) {
			log.info("Password for account " + token.getPrincipal() + " was incorrect!");
		} catch (LockedAccountException lae) {
			log.info("The account for username " + token.getPrincipal() + " is locked.  "
				+ "Please contact your administrator to unlock it.");
		}
		// ... catch more exceptions here (maybe custom ones specific to your
		// application?
		catch (AuthenticationException ae) {
			// unexpected condition? error?
		}
	}

	// say who they are:
	// print their identifying principal (in this case, a username):
	log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

	// test a role:
	if (currentUser.hasRole("schwartz")) {
		log.info("May the Schwartz be with you!");
	} else {
		log.info("Hello, mere mortal.");
	}

	// test a typed permission (not instance-level)
	if (currentUser.isPermitted("lightsaber:weild")) {
		log.info("You may use a lightsaber ring.  Use it wisely.");
	} else {
		log.info("Sorry, lightsaber rings are for schwartz masters only.");
	}

	// a (very powerful) Instance Level permission:
	if (currentUser.isPermitted("winnebago:drive:eagle5")) {
		log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  "
			+ "Here are the keys - have fun!");
	} else {
		log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
	}

	// all done - log out!
	currentUser.logout();

	System.exit(0);
}
 
示例10
public static void main(String[] args) {


        // The easiest way to create a Shiro SecurityManager with configured
        // realms, users, roles and permissions is to use the simple INI config.
        // We'll do that by using a factory that can ingest a .ini file and
        // return a SecurityManager instance:

        // Use the shiro.ini file at the root of the classpath
        // (file: and url: prefixes load from files and urls respectively):
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();

        // for this simple example quickstart, make the SecurityManager
        // accessible as a JVM singleton.  Most applications wouldn't do this
        // and instead rely on their container configuration or web.xml for
        // webapps.  That is outside the scope of this simple quickstart, so
        // we'll just do the bare minimum so you can continue to get a feel
        // for things.
        SecurityUtils.setSecurityManager(securityManager);

        // Now that a simple Shiro environment is set up, let's see what you can do:

        // get the currently executing user:
        Subject currentUser = SecurityUtils.getSubject();

        // Do some stuff with a Session (no need for a web or EJB container!!!)
        Session session = currentUser.getSession();
        session.setAttribute("someKey", "aValue");
        String value = (String) session.getAttribute("someKey");
        if (value.equals("aValue")) {
            log("Retrieved the correct value! [" + value + "]");
        }

        // let's login the current user so we can check against roles and permissions:
        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            token.setRememberMe(true);
            try {
                currentUser.login(token);
            } catch (UnknownAccountException uae) {
                log("There is no user with username of " + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {
                log("Password for account " + token.getPrincipal() + " was incorrect!");
            } catch (LockedAccountException lae) {
                log("The account for username " + token.getPrincipal() + " is locked.  " +
                        "Please contact your administrator to unlock it.");
            }
            // ... catch more exceptions here (maybe custom ones specific to your application?
            catch (AuthenticationException ae) {
                //unexpected condition?  error?
            }
        }

        //say who they are:
        //print their identifying principal (in this case, a username):
        log("User [" + currentUser.getPrincipal() + "] logged in successfully.");

        //test a role:
        if (currentUser.hasRole("schwartz")) {
            log("May the Schwartz be with you!");
        } else {
            log("Hello, mere mortal.");
        }

        //test a typed permission (not instance-level)
        if (currentUser.isPermitted("lightsaber:weild")) {
            log("You may use a lightsaber ring.  Use it wisely.");
        } else {
            log("Sorry, lightsaber rings are for schwartz masters only.");
        }

        //a (very powerful) Instance Level permission:
        if (currentUser.isPermitted("winnebago:drive:eagle5")) {
            log("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
                    "Here are the keys - have fun!");
        } else {
            log("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
        }

        //all done - log out!
        currentUser.logout();

        System.exit(0);

    }