一、Shiro是用来做权限的。

二、权限

1.基本概念:

(1)安全实体:要保护的数据。

(2)权限:是否有能力去操作(查看、修改、删除 )保护的数据。

2、权限的两个特性

(1)权限的继承性:A 包含 B,B无权限,但A有权限,此时B 的权限即为 A 的权限。如大厦里有公共厕所,进出大厦需要门禁,所以公共厕所的权限就是大厦的门禁权限。

(2)最近路劲匹配:如大厦某层有卫生间,要想到此卫生间需要有该层电梯权限,此时该卫生间的权限为该层电梯的权限,而不是大厦的门禁权限。

3.几个关键词

(1)认证:验证用户身份,即验证登录的用户名密码是否正确,用户是否被锁死。

(2)授权:决定是否有权限访问受保护的资源。

(3)加密:保护或隐藏受保护的资源。

(4)会话管理

(5)单点登录(SSO)

三、Shiro

1.核心组件

(1)Subject:当前用户。

(2)Shiro SecurityManager:Shiro 大管家。

(3)Realm:用于访问数据库。

2.Shiro SecurityManager

Shiro 的大管家管理着 Shiro 下的认证、授权、会话管理、缓存管理、以及 Realm 访问数据库,贯穿于始终的是加密。

3.用户、角色、权限

(1)概念:

  • 用户:通俗来讲,指的就是要登录的用户名密码。
  • 角色:权限的集合。
  • 权限:是否有能力去做某件事。

(2)关系

  • 权限作用于角色,角色是权限的一个集合
  • 角色作用于用户,用户是什么角色。

(3)维系关系

  • 用户——角色:用户角色中间表。
  • 角色——权限:角色权限中间表。

(4)以上所有的这些都归 Shiro 大管家来管理。

四、一个简单的官方的例子

1.需要导入的 jar 包。

2.官方demo。

/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/ import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* Simple Quickstart application showing how to use Shiro's API.
*
* @since 0.9 RC2
*/
public class Quickstart { private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class); public static void main(String[] args) { // The easiest way to create a Shiro SecurityManager with configured
// realms, users, roles and permissions is to use the simple INI config.
// We'll do that by using a factory that can ingest a .ini file and
// return a SecurityManager instance: // Use the shiro.ini file at the root of the classpath
// (file: and url: prefixes load from files and urls respectively):
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance(); // for this simple example quickstart, make the SecurityManager
// accessible as a JVM singleton. Most applications wouldn't do this
// and instead rely on their container configuration or web.xml for
// webapps. That is outside the scope of this simple quickstart, so
// we'll just do the bare minimum so you can continue to get a feel
// for things.
SecurityUtils.setSecurityManager(securityManager); // Now that a simple Shiro environment is set up, let's see what you can do: // get the currently executing user:
Subject currentUser = SecurityUtils.getSubject(); // Do some stuff with a Session (no need for a web or EJB container!!!)
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("-->Retrieved the correct value! [" + value + "]");
} // let's login the current user so we can check against roles and permissions:
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?
}
} //say who they are:
//print their identifying principal (in this case, a username):
log.info("-->User [" + currentUser.getPrincipal() + "] logged in successfully."); //test a role:
if (currentUser.hasRole("schwartz")) {
log.info("-->May the Schwartz be with you!");
} else {
log.info("Hello, mere mortal.");
} //test a typed permission (not instance-level)
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.");
} //a (very powerful) Instance Level permission:
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!");
} //all done - log out!
currentUser.logout(); System.exit(0);
}
}

说明:获取 SecurityManager ,认证,认证失败的几种情况,成功登陆后是否拥有某个角色,某个角色是否有某个权限。

[users]
root = secret, admin
guest = guest, guest
presidentskroob = 12345, president
darkhelmet = ludicrousspeed, darklord, schwartz
lonestarr = vespa, goodguy, schwartz [roles]
admin = *
schwartz = lightsaber:*
goodguy = winnebago:drive:eagle5

说明:Shiro.ini 文件,用来维系用户——角色——权限之间的关系。

3.ini 文件说明

[users]:用户名=密码,角色1,角色2

[roles]:角色=权限1,权限2

权限:

(1)用简单的字符串来表示一个权限。如:user

(2)多层次管理:如:user:query,user:edit,user:query,edit。第一部分为操作的领域,第二部分为执行的操作。可以使用通配符:user:*,*:query

(3)实例级权限:域:操作:实例

如:user:edit:manager 只能对 user 中的 manager 进行 edit。

通配符:user:edit:*、user:*:*、user:*:manager

等价:user:edit==user:edit:*、user == user:*:* 只能从字符串结尾处省略。

(4)可对比官方例子学习。

五、总结:

介绍了权限的基础,介绍了 Shiro 的 HelloWorld,要明白其中重要的部分,如:认证、授权,以及Shiro 是如何来做这两件事情的。介绍官方demo 的 ini 配置方式,只是想更加深刻的去理解

Shiro 的管理器,认证,授权,角色,权限等等这些概念。

Shiro —— 从一个简单的例子开始的更多相关文章

  1. 用一个简单的例子来理解python高阶函数

    ============================ 用一个简单的例子来理解python高阶函数 ============================ 最近在用mailx发送邮件, 写法大致如 ...

  2. Spring-Context之一:一个简单的例子

    很久之前就想系统的学习和掌握Spring框架,但是拖了很久都没有行动.现在趁着在外出差杂事不多,就花时间来由浅入深的研究下Spring框架.Spring框架这几年来已经发展成为一个巨无霸产品.从最初的 ...

  3. 关于apriori算法的一个简单的例子

    apriori算法是关联规则挖掘中很基础也很经典的一个算法,我认为很多教程出现大堆的公式不是很适合一个初学者理解.因此,本文列举一个简单的例子来演示下apriori算法的整个步骤. 下面这个表格是代表 ...

  4. 扩展Python模块系列(二)----一个简单的例子

    本节使用一个简单的例子引出Python C/C++ API的详细使用方法.针对的是CPython的解释器. 目标:创建一个Python内建模块test,提供一个功能函数distance, 计算空间中两 ...

  5. fitnesse - 一个简单的例子(slim)

    fitnesse - 一个简单的例子(slim) 2017-09-30 目录1 编写测试代码(Fixture code)2 编写wiki page并运行  2.1 新建wikiPage  2.2 运行 ...

  6. Struts2的配置和一个简单的例子

    Struts2的配置和一个简单的例子 笔记仓库:https://github.com/nnngu/LearningNotes 简介 这篇文章主要讲如何在 IntelliJ IDEA 中使用 Strut ...

  7. 一个简单的例子搞懂ES6之Promise

    ES5中实现异步的常见方式不外乎以下几种: 1. 回调函数 2. 事件驱动 2. 自定义事件(根本上原理同事件驱动相同) 而ES6中的Promise的出现就使得异步变得非常简单.promise中的异步 ...

  8. 一个简单的例子了解states

    在大规模的配置管理工作中,我们要编写大量的states.sls文件.top.sls是states系统的入口文件,它负责指定哪些设备调用哪些states.sls文件.statse的默认工作目录是在/sr ...

  9. 跨站脚本功攻击,xss,一个简单的例子让你知道什么是xss攻击

    跨站脚本功攻击,xss,一个简单的例子让你知道什么是xss攻击 一.总结 一句话总结:比如用户留言功能,用户留言中写的是网页可执行代码,例如js代码,然后这段代码在可看到这段留言的不同一户的显示上就会 ...

随机推荐

  1. [.net 面向对象编程基础] (21) 委托

    [.net 面向对象编程基础] (20)  委托 上节在讲到LINQ的匿名方法中说到了委托,不过比较简单,没了解清楚没关系,这节中会详细说明委托. 1. 什么是委托? 学习委托,我想说,学会了就感觉简 ...

  2. 项目开发之使用 maven

    本文将详述 maven 在软件项目中的使用.首先讲述 maven 的基本工作原理及环境的搭建.然后讲述开发及配置管理人员如何使用 maven,最后将介绍 maven 与 eclipse 集成使用. m ...

  3. 利用IFormattable接口自动参数化Sql语句

    提要 string.Format("{0},{1}",a,b)的用法大家都不陌生了,在很多项目中都会发现很多sql语句存在这样拼接的问题,这种做法很多"懒"程序 ...

  4. Javascript函数节流

    最近在做网页的时候有个需求,就是浏览器窗口改变的时候需要改一些页面元素大小,于是乎很自然的想到了window的resize事件,于是乎我是这么写的 <!DOCTYPE html> < ...

  5. 微软官网下载windows系统有点全

    第一步:访问:https://www.microsoft.com/zh-cn/software-download/windows10ISO/ 默认就只能下载win10,这怎么行呢.巨硬程序员貌似没做服 ...

  6. 项目管理师prince2

    项目管理师prince2 PRINCE2并不适合用于管理商业活动中的日常事物.商业日常事务通常是指组织机构日常运营中需要完成的那些工作.例如,公司it系统的维护,宾馆的房间整理,或者运营公司的客户呼叫 ...

  7. 制作Html标签以及表单、表格内容

    制作Html一般用DW(......),Html全称为(Hyper Text Markup Language   超文本标记语言) 文本就是平常电脑上的文本文档,只能存储文字,而超文本文档可以存储音乐 ...

  8. Atitit 开发2d游戏的技术选型attilax总结

    Atitit 开发2d游戏的技术选型attilax总结 1.1. 跨平台跨平台:一定要使用跨平台的gui技术,目前最好的就是h5(canvas,webgl,dom) +js了..1 1.2. 游戏前后 ...

  9. echart饼状图使用,打发时间。

    新公司,刚来几天,闲着没事,领导让我做些无关痛痒的活,优化报表统计!!!之前是用flash做的,现在要改成echart实现.好吧,之前没用过,抱着学习态度,研究了下.写点东西打发下时间,能帮到需要帮助 ...

  10. 仿SGI STL的traits技法

    首先是iterator traits,这个是用来萃取迭代器的特性的 #ifndef _STL_ITERATOR_H_ #define _STL_ITERATOR_H_ #include <cst ...