简介
Shiro是一个强大的简单易用的Java安全框架,主要用来更便捷的认证,授权,加密,会话管理。Shiro首要的和最重要的目标就是容易使用并且容易理解。
Shiro是一个有许多特性的全面的安全框架,下面这幅图可以了解Shiro的特性:
可以看出shiro除了基本的认证,授权,会话管理,加密之外,还有许多额外的特性。
Shiro 的目标是 Shiro 开发团队所说的"应用安全的四大基石" - 身份验证、授权、会话管理和密码学:
-
身份验证:有时被称为"登录",这是证明用户是谁,他们说他们的行为。
-
授权:访问控制过程,即确定"谁"可以访问"什么"。
-
会话管理:管理用户特定的会话,即使在非 Web 或 EJB 应用程序中。
-
密码学:使用加密算法确保数据安全,同时仍然易于使用。
在不同的应用环境中,还有其他功能可以支持和加强这些关注,特别是:
-
Web 支持:Shiro 的 Web 支持 API 帮助轻松保护 Web 应用程序的安全。
-
缓存:卡钦是阿帕奇希罗 API 的一级公民,以确保安全操作保持快速高效。
-
并发性:Apache Shiro 支持具有并发功能的多线程应用程序。
-
测试:存在测试支持,以帮助您编写单元和集成测试,并确保您的代码将按预期得到保护。
-
"运行为":允许用户承担其他用户身份的功能(如果允许),有时在管理方案中很有用。
-
"记住我":记住用户在跨会话中的身份,因此他们只需要在强制时登录。
配置shiro
-
配置依赖文件,这里需要注意如果你这里把配置加进去后报错的话,请你降低各个依赖的版本号
<dependencies> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies>
-
在resources中创建log4j.properties文件然后添加以下配置
# rootLogger参数分别为:根Logger级别,输出器stdout,输出器log log4j.rootLogger = info,stdout,log # 输出信息到控制台 log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = %d [%-5p] %l %rms: %m%n # 输出DEBUG级别以上的日志到D://logs/debug.log log4j.appender.log = org.apache.log4j.DailyRollingFileAppender log4j.appender.log.DatePattern = '.'yyyy-MM-dd log4j.appender.log.File = c:\axis.log log4j.appender.log.Encoding = UTF-8 #log4j.appender.log.Threshold = INFO log4j.appender.log.layout = org.apache.log4j.PatternLayout log4j.appender.log.layout.ConversionPattern = %d [%-5p] (%c.%t): %m%n
-
在resources中创建shiro.ini文件
注:如果这里你导入后没有高亮,可以Ctrl+Shift+A,召唤出输入框后搜索Plugins回车进入,然后在里面搜索ini进行安装就ok
# ----------------------------------------------------------------------------- # Users and their (optional) assigned roles # username = password, role1, role2, ..., roleN # ----------------------------------------------------------------------------- [users] root = secret, admin guest = guest, guest presidentskroob = 12345, president darkhelmet = ludicrousspeed, darklord, schwartz aihe = aihe, goodguy, client # ----------------------------------------------------------------------------- # Roles with assigned permissions # roleName = perm1, perm2, ..., permN # ----------------------------------------------------------------------------- [roles] admin = * client = look:* goodguy = winnebago:drive:eagle5
-
在java中创建Quickstart文件写入以下代码进行测试
import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.shiro.mgt.DefaultSecurityManager; import org.apache.shiro.realm.text.IniRealm; /** * Simple Quickstart application showing how to use Shiro's API. * * @since 0.9 RC2 */ public class Quickstart { private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class); 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):IniSecurityManagerFactory( DefaultSecurityManager securityManager = new DefaultSecurityManager(); IniRealm iniRealm = new IniRealm("classpath:shiro.ini"); securityManager.setRealm(iniRealm); // 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.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:wield")) { 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); } }
-
最后输出以下内容表示配置成功
-