快速开始
可以从官网下载一个QuickStart项目,开始使用Shiro。
shiro.ini
shiro.ini文件中定义了用户,角色,以及权限信息
[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = 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]
# '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
Quickstart.java
创建SecurityManager
实例
//使用shiro.ini
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
这样securitymanager
就包含了用户、角色和权限信息。
获取当前执行用户
Subject currentUser = SecurityUtils.getSubject();
判断用户是否登录
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?
}
获取登录用户信息
SecurityUtils.getSubject().getPrincipal();
判断用户角色
if (SecurityUtils.getSubject().hasRole("schwartz")){
...
}
判断用户权限
if (SecurityUtils.getSubject().isPermitted("lightsaber:wield")){
...
}
用户登出
SecurityUtils.getSubject().logout();
术语解释
Subject
任何与我们集成了Shiro的应用进行交互的人,第三方处理过程,服务甚至定时任务等。
Principals
Subject的身份信息属性,如姓名、身份证号、用户名等。
Credentials
用户验证身份信息的数据,如密码,生物特征数据等
Realms
安全模块特定的DAO,用于访问后台数据。每一个后台数据源都应该使用一个Realm。