Shiro(1.3.2)——入門
1.簡介:
Apache Shiro是Java的一個安全(許可權)框架,不僅可以用在Java SE環境,也可以用在Java EE環境。Shiro可以完成:認證、授權、加密、會話管理、與Web整合、快取等。
下載:http://shiro.apache.org/
2.功能簡介:
主要功能:
Authentication:認證(登入)。
Authorization:授權。
Session Management:管理Session,此Session不止Web環境下的HttpSession,它是Shiro自己的Session,在JavaSE的環境下也有。
Cryptography:加密。
支援:
Web Support:跟Java EE進行整合。
Concurrency:在多執行緒的情況下進行授權認證。
Testing:測試。
Caching:快取模組。
Run As:讓已經登入的使用者以另外一個使用者的身份來作業系統。
Remember Me:記住我。
3.Shiro架構:
3.1 外部架構:
Subject:應用程式碼直接互動的物件是Subject,也就是說Shiro對外API核心就是Subject。Subject代表了當前“使用者”,這個使用者不一定是具體的人,與當前應用互動的任何東西都是Subject,如網路爬蟲和機器人;與Subject的所有互動都會委託給SecurityManager;Subject是門面,SecurityManager是實際的執行者。
Shiro SecurityManager:安全管理器,所有與安全相關的操作都會與SecurityManager互動;並且管理著所有的Subject;是Shiro的核心;它負責和Shiro的其他元件互動。
Realm:Shiro從Realm獲取安全資料(如使用者、角色和許可權),也就是SecurityManager需要驗證身份,那麼它需要從Realm中獲得相應的使用者進行比較等等,Realm相當於是一個DataSource。
3.2 內部架構:
4.HelloWorld:
先匯入基本的Jar包到類路徑下:
匯入配置檔案和Java檔案到Src下面:
package com.shiro.helloworld; 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; public class Quickstart { private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class); public static void main(String[] args) { //使用工廠的方式獲取.ini配置檔案,返回一個SecurityManager例項 Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager = factory.getInstance(); //在這個例子中SecurityManager在JVM中是單例可訪問的 SecurityUtils.setSecurityManager(securityManager); //獲取當前的Subject Subject currentUser = SecurityUtils.getSubject(); //獲取Session並設定值 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 + "]"); } //測試當前的使用者是否已經被認證,即是否已經登入 if (!currentUser.isAuthenticated()) { //把使用者名稱和密碼封裝到UsernamePasswordToken物件 UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); //Remember Me token.setRememberMe(true); try { //執行登入 //能否登入成功取決於.ini配置檔案是否存在對應的使用者名稱和密碼 currentUser.login(token); } catch (UnknownAccountException uae) { //沒有指定賬戶時,丟擲該異常 log.info("----> There is no user with username of " + token.getPrincipal()); return; } catch (IncorrectCredentialsException ice) { //密碼不正確時,丟擲該異常 log.info("----> Password for account " + token.getPrincipal() + " was incorrect!"); return; } catch (LockedAccountException lae) { //使用者被鎖定時,丟擲該異常 log.info("The account for username " + token.getPrincipal() + " is locked. " + "Please contact your administrator to unlock it."); } catch (AuthenticationException ae) { //總的認證異常 //unexpected condition? error? } } log.info("----> User [" + currentUser.getPrincipal() + "] logged in successfully."); //測試是否有這個schwartz角色 if (currentUser.hasRole("schwartz")) { log.info("----> May the Schwartz be with you!"); } else { log.info("----> Hello, mere mortal."); return; } //測試使用者是否具備某一個行為 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."); } //同上,不過更具體,意思就是這個使用者是否可以刪除(delete)使用者(user)張三(zhangsan) if (currentUser.isPermitted("user:delete:zhangsan")) { 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!"); } System.out.println("---->" + currentUser.isAuthenticated()); //執行登出 currentUser.logout(); System.out.println("---->" + currentUser.isAuthenticated()); System.exit(0); } }
#
# 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.
#
# =============================================================================
# Quickstart INI Realm configuration
#
# For those that might not understand the references in this file, the
# definitions are all based on the classic Mel Brooks' film "Spaceballs". ;)
# =============================================================================
# -----------------------------------------------------------------------------
# Users and their assigned roles
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setUserDefinitions JavaDoc
# -----------------------------------------------------------------------------
[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = 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 'delete' (action) the user (type) with
# license plate 'zhangsan' (instance specific id)
goodguy = user:delete:zhangsan