一、SimpleAuthenticationInfo 簡介
SimpleAuthenticationInfo 是 Shiro 框架的核心組件之一,用於封裝身份驗證信息,實現自定義的身份認證和授權邏輯,結合相關的 Realm 實現調用。它通過封裝了認證成功後的用戶身份信息、密碼、鹽等,來提供給 Realm 實現進行後續的授權驗證。
二、SimpleAuthenticationInfo 的構造和方法
SimpleAuthenticationInfo 的構造方法如下:
SimpleAuthenticationInfo(Object principal, Object credentials, String realmName) SimpleAuthenticationInfo(Object principal, Object hashedCredentials, ByteSource credentialsSalt, String realmName)
構造方法參數說明:
- principal:用戶身份信息,通常為用戶名或用戶實體對象
- credentials:用戶憑證,即密碼或密碼的密文
- hashedCredentials:加密後的用戶憑證,即密碼的密文
- credentialsSalt:密碼加密的鹽值,通常使用用戶的唯一標識信息進行加密
- realmName:Realm 名稱,即應用程序或系統唯一的 Realm 標識
SimpleAuthenticationInfo 中比較常用的方法如下:
Object getPrinicipal() Object getCredentials() Object getCredentialsSalt() String getRealmName()
三、SimpleAuthenticationInfo 的實現示例
下面以自定義的 Realm 實現為例,介紹 SimpleAuthenticationInfo 的具體使用方法:
1. Realm 實現示例
public class CustomRealm extends AuthorizingRealm {
// 用於認證的方法
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// 獲取用戶輸入的用戶名和密碼
String userName = (String) token.getPrincipal();
String password = new String((char[]) token.getCredentials());
// 模擬數據庫中的用戶數據
if (!"admin".equals(userName)) {
throw new UnknownAccountException(); // 沒有找到賬號
}
if (!"123456".equals(password)) {
throw new IncorrectCredentialsException(); // 密碼錯誤
}
// 創建 SimpleAuthenticationInfo 對象
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userName, password, getName());
// 返回 SimpleAuthenticationInfo 對象
return authenticationInfo;
}
// 用於授權的方法
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
}
2. 用戶認證示例
// 獲取當前操作的用戶
Subject currentUser = SecurityUtils.getSubject();
// 創建一個身份驗證 Token
UsernamePasswordToken token = new UsernamePasswordToken("admin", "123456");
// 身份認證
try {
currentUser.login(token);
System.out.println("身份認證成功");
} catch (UnknownAccountException e) {
System.out.println("沒有找到賬戶");
} catch (IncorrectCredentialsException e) {
System.out.println("密碼錯誤");
} catch (AuthenticationException e) {
System.out.println("身份認證失敗");
}
3. 密碼加密示例
// 獲取鹽值
ByteSource salt = ByteSource.Util.bytes("admin");
// 獲取加密後的密碼
String newPassword = new SimpleHash("MD5", "123456", salt, 2).toHex();
System.out.println(newPassword);
四、SimpleAuthenticationInfo 的使用場景
SimpleAuthenticationInfo 主要用於自定義身份驗證邏輯,可以結合相關的 Realm 實現進行調用。在大部分應用程序中,都需要對用戶進行身份認證,而 SimpleAuthenticationInfo 提供了一種通用的方式,來封裝身份認證所需的信息,從而簡化了實現的複雜度,提高了程序的可擴展性和可維護性。
五、SimpleAuthenticationInfo 的注意事項
在使用 SimpleAuthenticationInfo 時需要注意以下幾點:
- SimpleAuthenticationInfo 是線程安全的,可以在多個線程中共享使用。
- SimpleAuthenticationInfo 必須與 Realm 一起使用,否則將無法實現自定義的身份認證邏輯。
- 在進行用戶身份認證時,強烈建議使用加密處理的密碼,尤其是在實際應用中對密碼進行存儲時。
原創文章,作者:ORHL,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/147739.html
微信掃一掃
支付寶掃一掃