创建一个SpringBoot应用,如何创建SpringBoot应用不在本文讨论范围,可参见官方文档。
添加依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency>
实例化SecurityManager
Shiro的核心是SecurityManager
,每一个Shiro应用必须有一个SecurityManager
。所以使用Shiro的第一件事情就是创建SecurityManager的实例。SecurityManager
的实现有很多的配置项,直接使用代码配置SecurityManager
会非常困难和痛苦。因此更推荐使用更简单而灵活的文本配置文件的形式来配置SecurityManager。
在Shiro中,默认的配置文件的格式是INI格式,当然,它也支持其他的配置文件的形式,如XML,YAML,JSON等常用格式。
在我们的第一个Shiro应用中,我们使用默认的INI配置文件的格式来配置SecurityManager
。
在src/main/resources目录下,新建shiro.ini文件,并写入以下内容:
# =============================================================================
# Tutorial INI configuration
#
# Usernames/passwords are based on the classic Mel Brooks' film "Spaceballs" :)
# =============================================================================
# -----------------------------------------------------------------------------
# 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
lonestarr = vespa, goodguy, schwartz
# -----------------------------------------------------------------------------
# Roles with assigned permissions
# roleName = perm1, perm2, ..., permN
# -----------------------------------------------------------------------------
[roles]
admin = *
schwartz = lightsaber:*
goodguy = winnebago:drive:eagle5
有了配置文件之后,就可以读取配置,来实例化SecurityManager.
//1.
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
//2.
SecurityManager securityManager = factory.getInstance();
//3.
SecurityUtils.setSecurityManager(securityManager);
获取Subject
Subject currentUser = SecurityUtils.getSubject();
获取Session
Session session = currentUser.getSession();
session.setAttribute( "someKey", "aValue" );
用户登录
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.
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);
}
角色与权限判断
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.");
}
退出登录
currentUser.logout(); //removes all identifying information and invalidates their session too.