shiro安全框架是目前為止作為登錄註冊最常用的框架,因為它十分的強大簡單,提供了認證、授權、加密和會話管理等功能 。
shiro能做什麼?
認證:驗證用戶的身份
授權:對用戶執行訪問控制:判斷用戶是否被允許做某事
會話管理:在任何環境下使用 Session API,即使沒有 Web 或EJB 容器。
加密:以更簡潔易用的方式使用加密功能,保護或隱藏數據防止被偷窺
Realms:聚集一個或多個用戶安全數據的數據源
單點登錄(SSO)功能。
為沒有關聯到登錄的用戶啟用 "Remember Me“ 服務
Shiro 的四大核心部分
Authentication(身份驗證):簡稱為“登錄”,即證明用戶是誰。
Authorization(授權):訪問控制的過程,即決定是否有權限去訪問受保護的資源。
Session Management(會話管理):管理用戶特定的會話,即使在非 Web 或 EJB 應用程序。
Cryptography(加密):通過使用加密算法保持數據安全
shiro的三個核心組件:
Subject :正與系統進行交互的人,或某一個第三方服務。所有 Subject 實例都被綁定到(且這是必須的)一個SecurityManager 上。
SecurityManager:Shiro 架構的心臟,用來協調內部各安全組件,管理內部組件實例,並通過它來提供安全管理的各種服務。當 Shiro 與一個 Subject 進行交互時,實質上是幕後的 SecurityManager 處理所有繁重的 Subject 安全操作。
Realms :本質上是一個特定安全的 DAO。當配置 Shiro 時,必須指定至少一個 Realm 用來進行身份驗證和/或授權。Shiro 提供了多種可用的 Realms 來獲取安全相關的數據。如關係數據庫(JDBC),INI 及屬性文件等。可以定義自己 Realm 實現來代表自定義的數據源。
shiro整合SSM框架:
1.加入 jar 包:以下jar包自行百度下載
2.配置 web.xml 文件
在web.xml中加入以下代碼—shiro過濾器。
<filter>
<filter-name>shiroFilter/<filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy/<filter-class>
<init-param>
<param-name>targetFilterLifecycle/<param-name>
<param-value>true/<param-value>
<filter-mapping>
<filter-name>shiroFilter/<filter-name>
<url-pattern>/*/<url-pattern>
3.在 Spring 的配置文件中配置 Shiro
Springmvc配置文件中:
<bean>
depends-on="lifecycleBeanPostProcessor"/>
<bean>
<property>
/<bean>
Spring配置文件中導入shiro配置文件:
<import>
新建applicationContext-shiro.xml
<beans>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean>
<property>
<bean>
class="shiro.MyRealm"
init-method="setCredentialMatcher">
/<bean>
<bean>
<property>
<property>
<bean>
class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<bean>
<property>
<property>
<property>
<property>
<property>
<value>
/shiro-logout = logout
/shiro-* = anon
/user.jsp = roles[user]
/admin.jsp = roles[admin]
/** = authc
/<bean>/<beans>
導入ehcache-shiro.xml配置文件:
<ehcache>
<diskstore>
<defaultcache>
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
<cache>
maxElementsInMemory="10000"
eternal="true"
overflowToDisk="true"
diskPersistent="true"
diskExpiryThreadIntervalSeconds="600"/>
<cache>
maxElementsInMemory="100"
eternal="false"
timeToLiveSeconds="600"
overflowToDisk="false"/>
到這一步,配置文件都基本準備好了,接下來要寫Realm方法了,新建shiro包,在包下新建MyRealm.java文件繼承 AuthorizingRealm
package shiro;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import bean.user;
import dao.userdao;
public class MyRealm extends AuthorizingRealm {
@Autowired
private userdao userdao;
String pass;
/**
*
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
Object principal = principalCollection.getPrimaryPrincipal();//獲取登錄的用戶名
if("admin".equals(principal)){ //兩個if根據判斷賦予登錄用戶權限
info.addRole("admin");
}
if("user".equals(principal)){
info.addRole("list");
}
info.addRole("user");
return info;
}
/*
* 用戶驗證
*
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//1. token 中獲取登錄的 username! 注意不需要獲取password.
Object principal = token.getPrincipal();
//2. 利用 username 查詢數據庫得到用戶的信息.
user user=userdao.findbyname((String) principal);
if(user!=null){
pass=user.getPass();
}
String credentials = pass;
//3.設置鹽值 ,(加密的調料,讓加密出來的東西更具安全性,一般是通過數據庫查詢出來的。 簡單的說,就是把密碼根據特定的東西而進行動態加密,如果別人不知道你的鹽值,就解不出你的密碼)
String source = "abcdefg";
ByteSource credentialsSalt = new Md5Hash(source);
//當前 Realm 的name
String realmName = getName();
//返回值實例化
SimpleAuthenticationInfo info =
new SimpleAuthenticationInfo(principal, credentials,
credentialsSalt, realmName);
return info;
}
//init-method 配置.
public void setCredentialMatcher(){
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
credentialsMatcher.setHashAlgorithmName("MD5");//MD5算法加密
credentialsMatcher.setHashIterations(1024);//1024次循環加密
setCredentialsMatcher(credentialsMatcher);
}
//用來測試的算出密碼password鹽值加密後的結果,下面方法用於新增用戶添加到數據庫操作的,我這裡就直接用main獲得,直接數據庫添加了,省時間
public static void main(String[] args) {
String saltSource = "abcdef";
String hashAlgorithmName = "MD5";
String credentials = "passwor";
Object salt = new Md5Hash(saltSource);
int hashIterations = 1024;
Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
System.out.println(result);
}
}
好了,接下來我們寫一個簡單的action來通過shiro登錄驗證。
//登錄認證
@RequestMapping("/shiro-login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password){
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
//執行認證操作.
subject.login(token);
}catch (AuthenticationException ae) {
System.out.println("登陸失敗: " + ae.getMessage());
return "/index";
}
return "/shiro-success";
}
//溫馨提示:記得在註冊中密碼存入數據庫前也記得加密哦,提供一個utils方法
//進行shiro加密,返回加密後的結果
public static String md5(String pass){
String saltSource = "blog";
String hashAlgorithmName = "MD5";
Object salt = new Md5Hash(saltSource);
int hashIterations = 1024;
Object result = new SimpleHash(hashAlgorithmName, pass, salt, hashIterations);
String password = result.toString();
return password;
}
好了,shiro登錄驗證到這裡完了,這個簡單的實例也應該能讓大家初步瞭解了
/<cache>/<cache>/<defaultcache>閱讀更多 碼農的小人生 的文章