Shiro的简单使用

快速开始

可以从官网下载一个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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值