shiro 認證問題
阿新 • • 發佈:2018-09-25
接口 配置文件 jsp name 鎖定 lin ... 用戶鎖定 system
@RequestMapping("/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password){
Subject currentUser = SecurityUtils.getSubject();
if (!currentUser.isAuthenticated()) {
// 把用戶名和密碼封裝為 UsernamePasswordToken 對象
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
// rememberme
token.setRememberMe(true);
try {
System.out.println("1. " + token.hashCode());
// 執行登錄.
currentUser.login(token);
}
// ... catch more exceptions here (maybe custom ones specific to your application?
// 所有認證時異常的父類.
catch (AuthenticationException ae) {
//unexpected condition? error?
System.out.println("登錄失敗: " + ae.getMessage());
}
}
return "redirect:/list.jsp";
}
如上所示,這是一個 shiro 登錄的 spring mvc 接口
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken token) throws AuthenticationException {
System.out.println("[SecondReaml] doGetAuthenticationInfo");
//1. 把 AuthenticationToken 轉換為 UsernamePasswordToken
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
//2. 從 UsernamePasswordToken 中來獲取 username
String username = upToken.getUsername();
//3. 調用數據庫的方法, 從數據庫中查詢 username 對應的用戶記錄
System.out.println("從數據庫中獲取 username: " + username + " 所對應的用戶信息.");
//4. 若用戶不存在, 則可以拋出 UnknownAccountException 異常
if("unknown".equals(username)){
throw new UnknownAccountException("用戶不存在!");
}
//5. 根據用戶信息的情況, 決定是否需要拋出其他的 AuthenticationException 異常.
if("monster".equals(username)){
throw new LockedAccountException("用戶被鎖定");
}
//6. 根據用戶的情況, 來構建 AuthenticationInfo 對象並返回. 通常使用的實現類為:
SimpleAuthenticationInfo
//以下信息是從數據庫中獲取的.
//1). principal: 認證的實體信息. 可以是 username, 也可以是數據表對應的用戶的實體類對象.
Object principal = username;
//2). credentials: 密碼.
Object credentials = null; //"fc1709d0a95a6be30bc5926fdb7f22f4";
if("admin".equals(username)){
credentials = "ce2f6417c7e1d32c1d81a797ee0b499f87c5de06";
}else if("user".equals(username)){
credentials = "073d4c3ae812935f23cb3f2a71943f49e082a718";
}
//3). realmName: 當前 realm 對象的 name. 調用父類的 getName() 方法即可
String realmName = getName();
//4). 鹽值.
ByteSource credentialsSalt = ByteSource.Util.bytes(username);
SimpleAuthenticationInfo info = null; //new SimpleAuthenticationInfo(principal, credentials, realmName);
info = new SimpleAuthenticationInfo("secondRealmName", credentials, credentialsSalt, realmName);
return info;
}
這個是自定義認證方法,在spring 配置文件中配置的。
我始終有一個疑惑,SimpleAuthenticationInfo 到底是怎麽能夠認證的用戶是否存在,用戶密碼是否正確 ?在不使用spring 的時候,會有一個 shiro.ini 配置文件,這個裏面有用戶名密碼等信息,但是在使用了 spring 這個配置文件就不需要了,然後我們自定義認證類,在自定義認證類中認證,到底是哪一步跟數據庫的用戶關聯的?SimpleAuthenticationInfo 做認證的信息是在哪裏 ?
String username = upToken.getUsername();
這個獲取的是用戶登錄的時候輸入的用戶名密碼 ? 還是說我們所判斷的用戶不存在、密碼錯誤、用戶鎖定 ,這些信息都是自己使用
throw new LockedAccountException("用戶被鎖定");
這種方式配判斷的 ?自己手動判斷 ?然後拋出異常 ?
我感覺我上述的所有的疑惑好像都是不清楚 SimpleAuthenticationInfo 來的運作。還是 AuthenticatingRealm 類的運作我不清楚 ?
shiro 認證問題