vlambda博客
学习文章列表

【Java Security】Apache Shiro:十分钟快速入门

"Apache Shiro (pronounced “shee-roh”, the Japanese word for ‘castle’) is a powerful and easy-to-use Java security framework that performs authentication, authorization, cryptography, and session management and can be used to secure any application - from the command line applications, mobile applications to the largest web and enterprise applications."


"Apache Shiro™ is a powerful and easy-to-use Java security framework that performs authentication, authorization, cryptography, and session management. With Shiro’s easy-to-understand API, you can quickly and easily secure any application – from the smallest mobile applications to the largest web and enterprise applications."


"Apache Shiro™ 是一个功能强大且易于使用的Java安全框架,它执行身份验证、授权、加密和会话管理。使用Shiro易于理解的API,您可以快速轻松地保护任何应用程序——从最小的移动应用程序到最大的web和企业应用程序。"




通过阅读这个简单快捷的教程,您应该完全了解开发人员如何在他们的应用程序中使用Shiro。你应该能在10分钟内完成。


Shiro可以在任何环境中运行,从最简单的命令行应用程序到最大的企业web和集群应用程序,但是我们将在这个快速启动的简单“main”方法中使用最简单的示例,这样您就可以感受到API。


使用的Shiro版本号:

Apache Shiro version 1.5.3


这个Quickstart.java中的代码上面的注释帮助您熟悉API。现在让我们把它分成几块,这样你就可以很容易地理解发生了什么。


在几乎所有环境中,都可以通过以下调用获取当前正在执行的用户

Subject currentUser = SecurityUtils.getSubject();


使用SecurityUtils.getSubject(),我们可以获取当前正在执行的Subject(主题)主题只是应用程序用户的特定于安全性的“视图”。实际上,我们想称之为“用户”,因为这“很有意义”,但我们决定不这么做:太多的应用程序都有自己的用户类/框架,我们不想与之冲突。此外,在安全领域,Subject(主题)一词实际上是公认的术语。好吧,继续…


独立应用程序中的getSubject()调用可能根据应用程序特定位置的用户数据返回Subject,而在服务器环境(例如web应用程序)中,它根据与当前线程或传入请求关联的用户数据获取Subject


既然你有一个Subject,你能用它做什么?


如果要在用户的应用程序的当前会话期间向用户提供内容,可以获取其会话:

Session session = currentUser.getSession();session.setAttribute( "someKey", "aValue" );


Session是一个Shiro特有的实例,它提供了您在常规HttpSessions中使用过的大部分内容,但是有一些额外的优点和一个很大的区别:它不需要HTTP环境!


如果部署在web应用程序中,默认情况下Session将基于HttpSession。但是,在非web环境中,比如这个简单的Quickstart例子,Shiro默认情况下会自动使用其企业会话管理。这意味着无论部署环境如何,您都可以在应用程序的任何层中使用相同的API。这将打开一个全新的应用程序世界,因为任何需要会话的应用程序都不需要强制使用HttpSession或EJB有状态会话bean(EJB Stateful Session Beans)。而且,任何客户端技术现在都可以共享会话数据。


所以现在你可以获取一个Subject和他们的Session。那些真正有用的东西呢,比如检查是否允许他们做一些事情,比如检查角色和权限?


好吧,我们只能为一个已知的用户做这些检查。上面的Subject实例代表当前用户,但是谁是当前用户?嗯,他们是匿名的——也就是说,直到他们至少登录一次。那么,让我们这样做:

if ( !currentUser.isAuthenticated() ) { //collect user principals and credentials in a gui specific manner //such as username/password html form, X509 certificate, OpenID, etc. //We'll use the username/password example here since it is the most common. //(do you know what movie this is from? ;) UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); //this is all you have to do to support 'remember me' (no config - built in!): token.setRememberMe(true); currentUser.login(token);}

就这样!再简单不过了。


但是如果他们的登录尝试失败了呢?您可以捕获各种特定异常,这些异常准确地告诉您发生了什么,并允许您相应地处理和响应:

try { currentUser.login( token ); //if no exception, that's it, we're done!} catch ( UnknownAccountException uae ) { //username wasn't in the system, show them an error message?} catch ( IncorrectCredentialsException ice ) { //password didn't match, try again?} catch ( LockedAccountException lae ) { //account for that username is locked - can't login. Show them a message?} ... more types exceptions to check if you want ...} catch ( AuthenticationException ae ) { //unexpected condition - error?}


有许多不同类型的异常,你可以检查,或抛出你自己的自定义条件雪罗可能不负责。有关更多信息,请参阅AuthenticationException JavaDoc。


“安全性最佳做法是向用户提供常规登录失败消息,因为您不想帮助攻击者试图闯入您的系统。”


好的,现在,我们有一个登录用户。我们还能做什么?


假设他们是谁:

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


我们还可以测试它们是否具有特定的角色:

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


我们还可以查看他们是否有权对某类实体采取行动:

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.");}


此外,我们还可以执行非常强大的实例级权限检查——查看用户是否有能力访问类型的特定实例:

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!");}


小菜一碟,对吧?


最后,当用户使用完应用程序后,他们可以注销:

currentUser.logout(); //removes all identifying information and invalidates their session too.


好吧,这是在应用程序开发人员级别使用Apache Shiro的核心内容。虽然有一些相当复杂的东西正在幕后进行,使这项工作如此优雅,这真的是它的全部。


但是您可能会问自己,“但是谁负责在登录期间获取用户数据(用户名和密码、角色和权限等),谁在运行时实际执行这些安全检查?“好吧,通过实现Shiro所称的Realm(领域)并将该Realm(领域)插入Shiro的配置,您就可以做到了。


但是,如何配置Realm在很大程度上取决于运行时环境。例如,如果您运行一个独立的应用程序,或者您有一个基于web的应用程序,或者一个基于Spring或JEE容器的应用程序,或者它们的组合。这种类型的配置不在本文QuickStart.java的范围内,因为它的目的是让您熟悉API和Shiro的概念。


当您准备好更详细地介绍时,您肯定想阅读Authentication Guide(身份验证指南)和Authorization Guide(授权指南)。然后可以转到其他文档,特别是参考手册,以回答任何其他问题。你可能还想加入用户邮件列表——你会发现我们有一个很好的社区,人们愿意随时提供帮助。


谢谢你的跟进。我们希望您喜欢使用Apache Shiro!


附:

工程结构:


shiro.ini:

# =============================================================================# Quickstart INI Realm configuration## For those that might not understand the references in this file, the# definitions are all based on the classic Mel Brooks' film "Spaceballs". ;)# =============================================================================
# -----------------------------------------------------------------------------# Users and their assigned roles## Each line conforms to the format defined in the# org.apache.shiro.realm.text.TextConfigurationRealm#setUserDefinitions JavaDoc# -----------------------------------------------------------------------------[users]# user 'root' with password 'secret' and the 'admin' roleroot = secret, admin# user 'guest' with the password 'guest' and the 'guest' roleguest = guest, guest# user 'presidentskroob' with password '12345' ("That's the same combination on# my luggage!!!" ;)), and role 'president'presidentskroob = 12345, president# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'darkhelmet = ludicrousspeed, darklord, schwartz# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'lonestarr = vespa, goodguy, schwartz
# -----------------------------------------------------------------------------# Roles with assigned permissions# # Each line conforms to the format defined in the# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc# -----------------------------------------------------------------------------[roles]# 'admin' role has all permissions, indicated by the wildcard '*'admin = *# The 'schwartz' role can do anything (*) with any lightsaber:schwartz = lightsaber:*# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with# license plate 'eagle5' (instance specific id)goodguy = winnebago:drive:eagle5


log4j.properties:

log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
# General Apache librarieslog4j.logger.org.apache=WARN
# Springlog4j.logger.org.springframework=WARN
# Default Shiro logginglog4j.logger.org.apache.shiro=INFO
# Disable verbose logginglog4j.logger.org.apache.shiro.util.ThreadContext=WARNlog4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN


Quickstart.java:

import org.apache.shiro.SecurityUtils;import org.apache.shiro.authc.*;import org.apache.shiro.config.IniSecurityManagerFactory;import org.apache.shiro.mgt.SecurityManager;import org.apache.shiro.session.Session;import org.apache.shiro.subject.Subject;import org.apache.shiro.util.Factory;import org.slf4j.Logger;import org.slf4j.LoggerFactory;

/** * 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): 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.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); }}


pom.xml:

<?xml version="1.0" encoding="UTF-8"?><!--suppress osmorcNonOsgiMavenDependency --><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
<parent> <groupId>org.apache.shiro.samples</groupId> <artifactId>shiro-samples</artifactId> <version>1.5.3</version> <relativePath>../pom.xml</relativePath> </parent>
<modelVersion>4.0.0</modelVersion> <artifactId>samples-quickstart</artifactId> <name>Apache Shiro :: Samples :: Quick Start</name> <packaging>jar</packaging>
<build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.6.0</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> </dependency>
<!-- configure logging --> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <scope>runtime</scope> </dependency> </dependencies>
</project>





小编:王枫


个人网站:


https://mapleeureka.github.io/index-ch.html