shiro学习
一些好的学习资源
http://www.aiuxian.com/article/p-1802736.html
shiro产生sessionId是通过UUID生成
一、概念
shiro是一个身份验证和角色管理的框架
二、用户信息配置
身份验证需要的信息(账号密码)以及角色管理(用户对应的角色)在shiro.ini的配置文件中配置,也可以选择将这两样信息放在数据库中
shiro.ini
如用户名为ly,密码为12345,角色为admin和user,则要这样配置 ly = 12345,admin,user
# =============================================================================
# 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
ly = 12345,admin,user
# -----------------------------------------------------------------------------
# Roles with assigned permissions
# roleName = perm1, perm2, ..., permN
# -----------------------------------------------------------------------------
[roles]
admin = *
schwartz = lightsaber:*
goodguy = winnebago:drive:eagle5
三、加载配置文件
1、引入依赖包
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.1.0</version>
</dependency>
<!-- Shiro uses SLF4J for logging. We'll use the 'simple' binding
in this example app. See http://www.slf4j.org for more info. -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
2、代码
//1.
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
//2.
SecurityManager securityManager = factory.getInstance();
//3.
SecurityUtils.setSecurityManager(securityManager);
四、做身份验证
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
if (!currentUser.isAuthenticated()) {
//这里是用户输入的账号ly和密码12345
UsernamePasswordToken token = new UsernamePasswordToken("ly", "12345");
token.setRememberMe(true);
try {
//调用login方法,shiro会将用户输入的信息与配置文件或数据库中的信息比对
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 (AuthenticationException ae) {
log.info("未知异常");
}
五、做角色验证
if (currentUser.hasRole("admin")) {
log.info("有admin角色");
} else {
log.info("没有该角色");
}
关于作者
后端程序员,五年开发经验,从事互联网金融方向。技术公众号「清泉白石」。如果您在阅读文章时有什么疑问或者发现文章的错误,欢迎在公众号里给我留言。