一、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 的管理器,認證,授權,角色,權限等等這些概念。