首頁>技術>

序言

大家好,我是老馬。

這次我們來一起學習下另一款 java 安全框架 shiro。

什麼是Apache Shiro?

Apache Shiro是一個功能強大且易於使用的Java安全框架,它為開發人員提供了一種直觀而全面的解決方案,用於身份驗證,授權,加密和會話管理。

實際上,它可以管理應用程式安全性的所有方面,同時儘可能避免干擾。它建立在可靠的介面驅動設計和OO原則的基礎上,可在您可以想象的任何地方實現自定義行為。

但是,只要對所有內容都使用合理的預設值,就可以像應用程式安全性一樣“輕鬆”。

快速開始

官方的例子是讓下載原始檔,老馬是直接從 github 下載的 mater 原始碼。

我們把核心的地方直接貼出來即可。

maven 依賴

最基礎的 shiro 演示,只需要引入下面的依賴即可。

<dependency>    <groupId>org.apache.shiro</groupId>    <artifactId>shiro-core</artifactId>    <version>1.2.2</version></dependency>
入門例子

內容看起來很多,主要是因為有很多註釋,實際上還是比較簡單的。

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:wield")) {            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);    }}
程式碼分析

下面我們針對這段程式碼做一下簡單的分析。

構建安全管理器

核心程式碼如下:

Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");SecurityManager securityManager = factory.getInstance();

實際上就是透過 shiro.ini 檔案中的配置,來建立一個 SecurityManager 例項。

然後透過 SecurityUtils.setSecurityManager(securityManager); 設定對應的安全管理器。

shiro.ini 的內容如下:

[users]# user 'root' with password 'secret' and the 'admin' roleroot = secret, admin# user 'guest' with the password 'guest' and the 'guest' roleguest = guest, guest# user 'presidentskroob' with password '12345' ("That's the same combination on# my luggage!!!" ;)), and role 'president'presidentskroob = 12345, president# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'darkhelmet = ludicrousspeed, darklord, schwartz# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'lonestarr = vespa, goodguy, schwartz# -----------------------------------------------------------------------------# Roles with assigned permissions# # Each line conforms to the format defined in the# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc# -----------------------------------------------------------------------------[roles]# 'admin' role has all permissions, indicated by the wildcard '*'admin = *# The 'schwartz' role can do anything (*) with any lightsaber:schwartz = lightsaber:*# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with# license plate 'eagle5' (instance specific id)goodguy = winnebago:drive:eagle5
當前主題

主題是一個相對更大的概念,我們也可以簡單的理解為當前使用者。

Subject currentUser = SecurityUtils.getSubject();

這個工具方法,實際上是透過 ThreadLocal 維護了當前的使用者資訊,如果不存在,會建立預設的主題資訊。

當獲取到當前使用者之後,我們就可以進行相關的操作了。

session 操作

寫過 web 的同學對 HttpSession 肯定非常熟悉。

shiro 設計非常巧妙的一點,就是有一套獨立的 session API,讓 session 的管理脫離 web 也可以使用,這是非常棒的設計。

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

我們設定對應的值,並且取出來進行判斷。

此時日誌也會輸出:

2020-12-27 18:59:47,288 INFO [Quickstart] - Retrieved the correct value! [aValue]
使用者登入

我們在設計 web 應用的時候,最關心的肯定還是使用者的角色許可權等資訊。

我們前面的 currentUser 就代表著當前的使用者,當然預設使用者實際上是匿名的。

需要我們進行一次登入:

if (!currentUser.isAuthenticated()) {    UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");    token.setRememberMe(true);    try {        currentUser.login(token);    } catch (UnknownAccountException uae) {        // 省略後續的各種異常    }}

這個登入的賬戶密碼,是前面我們配置在 shiro.ini 檔案中的:

# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'lonestarr = vespa, goodguy, schwartz

當然,這裡的 shiro 提供的異常是非常詳細的,這可以方便我們更好的定位問題。

但是當用戶登入的時候,我們提示應該避免這麼詳細,為什麼呢?

主要是避免有使用者惡意撞庫,提示一般都是【使用者名稱或者密碼錯誤】。不讓惡意使用者知道對應的使用者名稱資訊。

登入成功之後,可以輸出對應的使用者名稱資訊:

log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

對應的日誌如下:

2020-12-27 18:59:47,289 INFO [Quickstart] - User [lonestarr] logged in successfully. 
許可權校驗

使用者成功登陸之後,我們就可以獲取到使用者 lonestarr 對應的角色 goodguy 和 schwartz。

這樣,就可以判斷當前使用者是否有具體的許可權,比如選單許可權,操作許可權等。這也是我們一般最常用的功能。

測試角色

測試當前使用者是否擁有指定的角色:

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

日誌如下:

2020-12-27 18:59:47,290 INFO [Quickstart] - May the Schwartz be with you!
測試許可權

測試當前使用者是否擁有指定的許可權:

if (currentUser.isPermitted("lightsaber:wield")) {    log.info("You may use a lightsaber ring.  Use it wisely.");} else {    log.info("Sorry, lightsaber rings are for schwartz masters only.");}

我們在 shiro.ini 中配置了對應的操作許可權:

# The 'schwartz' role can do anything (*) with any lightsaber:schwartz = lightsaber:*

所以可以針對 lightsaber 為所欲為~

日誌如下:

2020-12-27 18:59:47,290 INFO [Quickstart] - You may use a lightsaber ring.  Use it wisely.

另外一個方法也是類似的,此處不再贅述。

使用者登出

當我們全部操作完成以後,可以執行使用者的登出操作。

//all done - log out!currentUser.logout();
小結

shiro 設計的非常簡潔,功能也非常的強大,可以滿足我們大部分許可權開發功能。

個人感覺這個框架肯定是有多年登入經驗的大佬設計的,api 和背後的理念非常值得學習。

當然這裡作為入門的例子,整體比較簡單。我們日常開發一般都是使用資料庫進行賬戶資訊持久化,密碼也會進行對應的加密處理。

這些 shiro 都已經考慮到了,我們後續會進行講解。

我是老馬,期待與你的下次相遇。

11
最新評論
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • 專門畫了9張圖,搞懂設計模式6大原則,這次應該可以了吧