Shiro的subject实质上是当前执行用户的特定视图。
Shiro的subject实质上是当前执行用户的特定视图。
通过org.apache.shiro.SecurityUtils可以查询当前执行用户:
Subject currentUser = SecurityUtils.getSubject();
获取当前执行用户的session:
(在非web、非EJB的情况下,Shiro自动使用自带session;如果是web或者EJB应用,则Shiro自动使用HttpSession,不需要人为改变。)
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.
//(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);
}
验证失败,提示信息:
ry {
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?
}
案例二(展示当前用户信息):
//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.");
}
案例五(退出登录):
currentUser.logout(); //removes all identifying information and invalidates their session too.
Shiro支持创建subject的实例,但不推荐。因为我们平常可以直接通过getSubject来获取当前执行用户。个别情况需要创建subject:
1.当前没有用户可以与系统进行交互,但是为保持系统的运行,需要假设一个用户,此时可以创建一个subject,比如admin用户。
2.集成测试时,需要创建一个临时的subject用以进入下一步的测试。
3.应用的后台进程运行的时候,需要一个subject。
(如果已经拥有了一个subject,但是需要和其他线程共享的话,需要调用Subject.associateWith*方法。)
subject的创建
案例六(Subject.Builder,创建subject,而无需知道其中细节,会访问到SecurityManager的SecurityUtils.getSecurityManager()方法。):
Subject subject = new Subject.Builder().buildSubject()
案例七(自建securityManager):
SecurityManager securityManager = //acquired from somewhere
Subject subject = new Subject.Builder(securityManager).buildSubject();
案例八(利用session创建新的subject):
Serializable sessionId = //acquired from somewhere
Subject subject = new Subject.Builder().sessionId(sessionId).buildSubject();
案例九(创建subject,并将其属性映射到验证属性中):
Object userIdentity = //a long ID or String username, or whatever the "myRealm" requires
String realmName = "myRealm";
PrincipalCollection principals = new SimplePrincipalCollection(userIdentity, realmName);
Subject subject = new Subject.Builder().principals(principals).buildSubject();
将自建的subject与线程进行绑定:
1.系统的自动绑定,Subject.execute*方法的调用。
2.手动的绑定。
3.利用已绑定的线程来绑定到新的线程,Subject.associateWith*方法的调用。
(subject与线程绑定,则可以在线程执行过程中取到信息;subject与线程取消绑定,则线程可以被回收。)
案例十(调用execute方法,参数为runable实例,实现subject的自动绑定与拆除):
Subject subject = //build or acquire subject
subject.execute( new Runnable() {
public void run() {
//subject is 'bound' to the current thread now
//any SecurityUtils.getSubject() calls in any
//code called from here will work
}
});
//At this point, the Subject is no longer associated
//with the current thread and everything is as it was before
案例十一(调用execute方法,参数为callable实例,实现subject的自动绑定与拆除):
Subject subject = //build or acquire subject
MyResult result = subject.execute( new Callable<MyResult>() {
public MyResult call() throws Exception {
//subject is 'bound' to the current thread now
//any SecurityUtils.getSubject() calls in any
//code called from here will work
...
//finish logic as this Subject
...
return myResult;
}
});
//At this point, the Subject is no longer associated
//with the current thread and everything is as it was before
案例十二(spring远程调用subject):
Subject.Builder builder = new Subject.Builder();
//populate the builder's attributes based on the incoming RemoteInvocation
...
Subject subject = builder.buildSubject(); return subject.execute(new Callable() {
public Object call() throws Exception {
return invoke(invocation, targetObject);
}
});
线程池的清理:
Subject subject = new Subject.Builder()...
ThreadState threadState = new SubjectThreadState(subject);
threadState.bind();
try {
//execute work as the built Subject
} finally {
//ensure any state is cleaned so the thread won't be
//corrupt in a reusable or pooled thread environment
threadState.clear();
}
案例十三(callable):
Subject subject = new Subject.Builder()...
Callable work = //build/acquire a Callable instance.
//associate the work with the built subject so SecurityUtils.getSubject() calls works properly:
work = subject.associateWith(work);
ExecutorService executorService = new java.util.concurrent.Executors.newCachedThreadPool();
//execute the work on a different thread as the built Subject:
executor.execute(work);
案例十四(runable):
Subject subject = new Subject.Builder()...
Runnable work = //build/acquire a Runnable instance.
//associate the work with the built subject so SecurityUtils.getSubject() calls works properly:
work = subject.associateWith(work);
Executor executor = new java.util.concurrent.Executors.newCachedThreadPool();
//execute the work on a different thread as the built Subject:
executor.execute(work);
Shiro的subject实质上是当前执行用户的特定视图。的更多相关文章
- 自动化运维,远程交互从服务器A上ssh到服务器B上,然后执行服务器B上的命令。
第一种: ftp -v -n 192.168.0.1 21 <<! user ftp ftp123 bay ! 第二种: { echo -e "\n" echo -e ...
- Maven依赖中的scope详解,在eclipse里面用maven install可以编程成功,到服务器上用命令执行报VM crash错误
Maven依赖中的scope详解 项目中用了<scope>test</scope>在eclipse里面用maven install可以编译成功,到服务器上用命令执行报VM cr ...
- 工作流JBPM_day02:3-预定义的活动1_4-预定义的活动2+在图片上高亮显示正在执行的上活动
工作流JBPM_day02:3-预定义的活动1 工作流JBPM_day02:4-预定义的活动2+在图片上高亮显示正在执行的上活动 活动 Activity 预先定义好的活动 Start开始活动 End结 ...
- 痞子衡嵌入式:在串口波特率识别实例里逐步展示i.MXRT上提升代码执行性能的十八般武艺
大家好,我是痞子衡,是正经搞技术的痞子.今天痞子衡给大家介绍的是在串口波特率识别实例里逐步展示i.MXRT上提升代码执行性能的十八般武艺. 恩智浦 MCU SE 团队近期一直在加班加点赶 SBL 项目 ...
- python paramiko实现ssh上传下载执行命令
paramiko ssh上传下载执行命令 序言 最近项目经常需要动态在跳板机上登录服务器进行部署环境,且服务器比较多,每次完成所有服务器到环境部署执行耗费大量时间.为了解决这个问题,根据所学的执行实现 ...
- Oracle DB 执行用户管理的备份和恢复
• 说明用户管理的备份和恢复与服务器管理的备份和恢复 之间的差异 • 执行用户管理的数据库完全恢复 • 执行用户管理的数据库不完全恢复 备份和恢复的使用类型 数据库备份和恢复的类型包括: • 用户管理 ...
- SQL 禁止在 .NET Framework 中执行用户代码。启用 "clr enabled" 配置选项
注:本文摘自:http://blog.csdn.net/heshengfen123/article/details/3597125 在执行SQL脚本过程中如果出现 禁止在 .NET Framework ...
- 修改php执行用户,并使其拥有root权限
useradd apachephp vi /etc/httpd/conf/httpd.conf 将组和用户修改成apachephp,重启apache,然后用lsof -i:80查看apache的执行用 ...
- Dajngo——10 请求与响应 文件上传 GET和POST请求 类视图
Dajngo——10 HttpRequest对象 HttpResponse对象及子类 form标签中的GET和POST GET提交方式 POST提交方式 request得GET和POST属性 文件上传 ...
随机推荐
- win10 tortoiseSVN文件夹及文件图标不显示解决方法
对于SVN来说,因为每个图标都代表着不同的含义,预示着不同的状态,是指示灯的作用,如果没有正确的图标很可能造成数据的丢失等. 输入:win+R,输入regedit,调出注册表信息,按下Ctrl+F,在 ...
- SQL Server 2012 从备份中还原数据库
1.首先把原数据库备份,检查原数据库的日志文件是否太大,如果过于大应该先收缩数据库日志 2.把备份的数据库文件在目标SQL Server还原,点击数据库,选择“还原文件或文件组” 3.如果需要修改还原 ...
- redhat修复hostname主机名
1.修改文件vi /etc/sysconfig/network下的hostname,如: NETWORKING=yes HOSTNAME=master 2.修改文件:vi /etc/hosts 127 ...
- OAuth学习总结
1.为什么需要OAuth? 新浪微博就是你的家.偶尔你会想让一些人(第三方应用)去你的家里帮你做一些事,或取点东西.你可以复制一把钥匙(用户名和密码)给他们,但这里有三个问题: 1)别人拿了钥匙后可以 ...
- U-Boot编译过程完全分析
2.1 U-Boot Makefile分析 2.1.1 U-Boot编译命令 对于mini2440开发板,编译U-Boot需要执行如下的命令: $ make m ...
- bzoj3995
线段树 额 计蒜客竟然把这个出成noip模拟题... 这个东西很像1018,只不过维护的东西不太一样 然后我参考了fuxey大神的代码,盗一波图 具体有这五种情况,合并请看代码,自己写了一个结果wa了 ...
- Spring--quartz中cronExpression配置说明
Spring--quartz中cronExpression Java代码 字段 允许值 允许的特殊字符 秒 0-59 , - * / 分 ...
- 彻底解决SysFader:IEXPLORE.EXE应用程序错误
彻底解决SysFader:IEXPLORE.EXE应用程序错误 转载于 西部e网(weste.net) 最近安装了IE8浏览器玩玩,但是发现一个严重的问题,就是在访问某些页面的时候,经常会出现“ysF ...
- bzoj 1017: [JSOI2008]魔兽地图DotR【树形dp+背包】
bzoj上是一个森林啊--? dp还是太弱了 设f[i][j][k]为到点i,合成j个i并且花费k金币能获得的最大力量值,a[i]为数量上限,b[i]为价格,p[i]为装备力量值 其实这个状态设计出来 ...
- bzoj 4568: [Scoi2016]幸运数字【树链剖分+线段树+线性基】
一眼做法,好处是好想好写坏处是常数大,容易被卡(bzoj loj 洛谷开O2 能AC,不开有90分-- 大概就是树剖之后维护线段树,在线段树的每个节点上上维护一个线性基,暴力\( 60^2 \)的合并 ...