SecurityManager是Shiro的绝对核心,不同于java.lang.SecurityManager,每个应用程序都要有一个SecurityManager.

所以我们第一件事就是配置一个SecurityManager实例.

配置:

我们可以直接实例化SecurityManager类,Shiro的SecurityManger的实现有很多配置选项和内部组件.

可以通过文本类型的配置文件配置.Shiro提供了ini格式的配置文件.

相较于xml,ini更加易读,也无需太多依赖.

可以简单配置简单对象图,如SecurityManager.

    public static void main(String[] args) {

    log.info("My First Apache Shiro Application");

    //1.工厂模式,通过配置文件来构建工厂
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); //2.通过工厂来得到SecurityManager的实例
SecurityManager securityManager = factory.getInstance(); //3.设置(2)中得到的实例为当前进程的SecurityManager
SecurityUtils.setSecurityManager(securityManager);
//4.根据(3)中的设置,getSubject()可以使用了.得到主题对象(或者称之为Shiro的'用户')
Subject currentUser = SecurityUtils.getSubject();
//5. Shiro的session不需要HTTP环境,但能提供其相似功能以及额外的优势
Session session = currentUser.getSession();
session.setAttribute( "someKey", "aValue" );

Shiro will automatically use its Enterprise Session Management by default.这意味着在任何层,任意开发环境,你可以在你的程序中得到相同的API.

这打开了新世界的大门: 一些程序需要session不再被迫使用HttpSession或者EJB Stateful Session Beans.

任何客户端数据都可以共享session数据.

===我们可以获得一个Subject以及他们的Session. 以上的Subject实例代表着当前用户.

note:谁是当前用户呢?

Well, they’re anonymous - that is, until they log in at least once. So, let’s do that:

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);
}

以上是最简单的方法了.

但是登录失败了呢?可以捕捉一系列排序号的指定异常来精确诊断哪一步出问题了.

try {
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?
}

更多异常参考:Authentication异常的详细信息

Handy Hint:

Security best practice is to give generic login failure messages to users because you do not want to aid an attacker trying to break into your system.

Ok, so by now, we have a logged in user. What else can we do?

Let’s say who they are:

//print their identifying principal (in this case, a username):
log.info( "User [" + currentUser.getPrincipal() + "] logged in successfully." );

We can also test to see if they have specific role or not:

if ( currentUser.hasRole( "schwartz" ) ) {
log.info("May the Schwartz be with you!" );
} else {
log.info( "Hello, mere mortal." );
}

We can also see if they have a permission to act on a certain type of entity:

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.");
}

Also, we can perform an extremely powerful instance-level permission check - the ability to see if the user has the ability to access a specific instance of a type:

if ( currentUser.isPermitted( "winnebago:drive:eagle5" ) ) {
log.info("You are permitted to 'drive' the 'winnebago' with license plate (id) 'eagle5'. " +
"Here are the keys - have fun!");
} else {
log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}

Piece of cake, right?

Finally, when the user is done using the application, they can log out:

currentUser.logout(); //removes all identifying information and invalidates their session too.

[Shiro] tutorial 1 :SecurityManager and Subject的更多相关文章

  1. Shiro源码分析之Subject和SecurityManager

    Subject 毫无疑问,Subject是Shiro最重要的一个概念. “Subject”只是一个安全术语,意味着应用程序用户的特定于安全性的“视图”.Shiro Subject实例代表单个应用程序用 ...

  2. shiro错误No SecurityManager accessible to the calling code

    Shire在Web.xml中shiroFilter的Mapping配置错误 org.apache.shiro.UnavailableSecurityManagerException: No Secur ...

  3. shiro实战系列(十)之Subject

    毫无疑问,在 Apache Shiro 中最重要的概念就是 Subject.'Subject'仅仅是一个安全术语,是指应用程序用户的特定 安全的“视图”.一个 Shiro Subject 实例代表了一 ...

  4. Shiro的认证原理(Subject#login的背后故事)

    登录操作一般都是我们触发的: Subject subject = SecurityUtils.getSubject(); AuthenticationToken authenticationToken ...

  5. Shiro遇到的SecurityManager红色警告

    问题如图 需要添加一个导入 import org.apache.shiro.mgt.SecurityManager; 这样就不会报错了

  6. SpringBoot2整合Shiro报错 UnavailableSecurityManagerException: No SecurityManager accessible to the calling code 【已解决】

    SpringBoot集成Shiro报错 UnavailableSecurityManagerException: No SecurityManager accessible to the callin ...

  7. Apache Shiro系列教程之二:十分钟上手Shiro

    在本教程中,我们会写一个简单的.仅仅输出一些内容命令行程序,从而对Shiro有一个大体的感觉. 一.准备工作 本教程需要Java1.5+,并且我们用Maven生成项目,当然Maven不是必须的,你也可 ...

  8. Apache Shiro Architecture--官方文档

    原文地址:http://shiro.apache.org/architecture.html Apache Shiro's design goals are to simplify applicati ...

  9. shiro入门实例,基于ini配置

    基于ini或者关系数据库的,其实都是一样的,重要的是思想. # ==================================================================== ...

随机推荐

  1. TextField widgets require a Material widget ancestor

    TextField widget需要被包裹在Scaffold widget中,否则会报错

  2. Python3.0科学计算学习之绘图(二)

    (1) np.mashgrid()函数:-----生成网络点坐标矩阵,可以是二维网络矩阵,也可以是三维网络矩阵.其中,每个交叉点就是网络点,描述这些网络点的矩阵就是坐标矩阵(横坐标矩阵X中的每个元素与 ...

  3. if __name__ == '__main__' 这段代码怎么理解???

    __name__是内置变量,可用于表示当前模块的名字,而“__main__”等于当前执行文件的名称. 两个名称搞不清没关系,往下看待会解释 对很多编程语言来说,程序都需要一个入口,例如C系列.Java ...

  4. SetFileAttributes 设置属性

    #include <Windows.h> #include <tchar.h> int WINAPI _tWinMain(HINSTANCE hInstance, HINSTA ...

  5. 5分钟安装 关于win10安装composer PHP 用来管理依赖(dependency)关系的工具

    1.在你的phpstudy或者wamp中开启extension=php_openssl.dll扩展 (php配置文件)并配置好php的环境变量 2.在与你安装phpstudy和wamp不一样的盘中创建 ...

  6. 设置VS2017背景图片

    设置方法很简单:安装扩展ClaudiaIDE 1.在这里下载扩展,https://visualstudiogallery.msdn.microsoft.com/9ba50f8d-f30c-4e33-a ...

  7. 淘宝客订单api处理优化

    首选我们看看api定义: http://open.taobao.com/api.htm?docId=38078&docType=2&scopeId=14474 注意下span这个参数 ...

  8. java数组集合元素的查找

    java数组和集合的元素查找类似,下面以集合为例. 数组集合元素查找分为两类: 基本查找: 二分折半查找: 基本查找: 两种方式都是for循环来判断,一种通过索引值来判断,一种通过数组索引判断. 索引 ...

  9. 利用 html js判断 客户端是否安装了某个app 安装了就打开 否则跳转到gp

    三种方式 方式一:简单的进行打开app,延时操作若未打开直接跳gp function isInstalled(){ var urlFrag = 'somepars'; var the_href = ' ...

  10. Jenkins>>>应用篇>>>插件使用>>>Publish over SSH

    依赖环境 SSH: 远程机开启SSH服务.同意Jenkins所在机器通过SSH服务登录到远程机运行脚本. 能够设置SSH使用username/password或通过key登录,SSH配置请查专门的资料 ...