框架之shiro(01)核心功能"/>
Java框架之shiro(01)核心功能
shiro 概述
一、shiro 简介
1、shiro 是什么
- Shiro 是一个强大灵活的开源安全框架,可以用于应用程序的身份验证,授权,会话管理和加密。
2、主要功能
- Authentication:有时也简称为“登录”,这是一个证明用户是他们所说的他们是谁的行为。
- Authorization:访问控制的过程,也就是决定什么用户访问什么资源。
- Session Management:管理用户特定的会话,即使在非 Web 或 EJB 应用程序。
- Cryptography:通过使用加密算法保持数据安全同时易于使用。
3、支持特性
- Web支持:Shiro 提供的 web 支持 api ,可以很轻松的保护 web 应用程序的安全。
- 缓存:缓存是 Apache Shiro 保证安全操作快速、高效的重要手段。
- 并发:Apache Shiro 支持多线程应用程序的并发特性。
- 测试:支持单元测试和集成测试,确保代码和预想的一样安全。
- Run As:这个功能允许用户假设另一个用户的身份(在许可的前提下)。
- Remember Me:跨 session 记录用户的身份,只有在强制需要时才需要登录。
二、第一个shiro程序
1、使用说明
- maven构建工程,log4j输出日志
- idea终端里,当前工程目录下使用 mvn compile exec:java 命令运行程序,直接运行测试的类不会输出测试的信息
2、目录结构
3、关键文件内容及代码
- pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi=""xmlns=".0.0"xsi:schemaLocation=".0.0
.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.stan</groupId><artifactId>shiro</artifactId><version>1.0.0-SNAPSHOT</version><name>shiro-start</name><packaging>jar</packaging><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>2.0.2</version><configuration><source>1.8</source><target>1.8</target><encoding>${project.build.sourceEncoding}</encoding></configuration></plugin><!-- This plugin is only to test run our little application. It is notneeded in most Shiro-enabled applications: --><plugin><groupId>org.codehaus.mojo</groupId><artifactId>exec-maven-plugin</artifactId><version>1.1</version><executions><execution><goals><goal>java</goal></goals></execution></executions><configuration><classpathScope>test</classpathScope><mainClass>QuickStart</mainClass></configuration></plugin></plugins></build><dependencies><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><version>1.1.0</version></dependency><!-- Shiro use SLF4J for logging. We'll use the 'simple' bindingin this example app. See for more info. --><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-simple</artifactId><version>1.6.1</version><scope>test</scope></dependency></dependencies>
</project>
- shiro配置文件
[users]
root = secret, admin
guest = guest, guest
presidentskroob = 12345, president
darkhelmet = ludicrousspeed, darklord, schwartz
lonestarr = vespa, goodguy, schwartz[roles]
admin = *
schwartz = lightsaber:*
goodguy = winnebago:drive:eagle5
- log4j配置文件
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n# General Apache libraries
log4j.logger.apache=WARN
# Spring
log4j.logger.springframework=WARN
# Default Shiro logging
log4j.logger.apache.shiro=TRACE
# Disable verbose logging
log4j.logger.apache.shiro.util.ThreadContext=WARN
log4j.logger.apache.shiro.cache.ehcache.EhCache=WARN
- 测试类
public class QuickStart {private static final transient Logger log = LoggerFactory.getLogger(QuickStart.class);public static void main(String[] args) {log.info("My First Apache Shiro Application");Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.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 (value.equals("aValue")) {log.info("Retrieved the correct vlaue! [" + value + "]");}//let's login the current user so we can check against roles and permissions:if (!currentUser.isAuthenticated()) {UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "1223");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);}
}
三、shiro 架构
1、架构图
更多推荐
Java框架之shiro(01)核心功能
发布评论