Shiro——从一个简单的例子开始

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Shiro——从⼀个简单的例⼦开始
⼀、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
*
* /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")) {
("-->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) {
("-->There is no user with username of " + token.getPrincipal());
} catch (IncorrectCredentialsException ice) {
("-->Password for account " + token.getPrincipal() + " was incorrect!");
} catch (LockedAccountException lae) {
("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):
("-->User [" + currentUser.getPrincipal() + "] logged in successfully.");
//test a role:
if (currentUser.hasRole("schwartz")) {
("-->May the Schwartz be with you!");
} else {
("Hello, mere mortal.");
}
//test a typed permission (not instance-level)
if (currentUser.isPermitted("lightsaber:weild")) {
("-->You may use a lightsaber ring. Use it wisely.");
} else {
("Sorry, lightsaber rings are for schwartz masters only.");
}
//a (very powerful) Instance Level permission:
if (currentUser.isPermitted("winnebago:drive:eagle5")) {
("-->You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +
"Here are the keys - have fun!");
} else {
("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 的管理器,认证,授权,⾓⾊,权限等等这些概念。

相关文档
最新文档