shiro框架的UsernamePasswordToken與對應Realm中的AuthenticationToken的一點比較
阿新 • • 發佈:2018-12-05
這裡以簡單的登陸為例子
控制器對應的登陸方法:
@RequestMapping(value = "/login", method = RequestMethod.GET) public String login(@RequestParam("username") String username, @RequestParam("password") String password){ // 獲取當前的 Subject. 呼叫 SecurityUtils.getSubject(); Subject currentUser = SecurityUtils.getSubject(); // 測試當前的使用者是否已經被認證. 即是否已經登入. // 調動 Subject 的 isAuthenticated() if (!currentUser.isAuthenticated()) { // 把使用者名稱和密碼封裝為 UsernamePasswordToken 物件 UsernamePasswordToken token = new UsernamePasswordToken(username, password); // rememberme token.setRememberMe(true); try { System.out.println("UsernamePasswordToken:"); System.out.println("hashCode:" + token.hashCode()); System.out.println("Principal:" + token.getPrincipal()); System.out.println("Credentials:" + String.valueOf((char[]) token.getCredentials())); System.out.println("host:" + token.getHost()); System.out.println("Username:" + token.getUsername()); System.out.println("Password:" + String.valueOf(token.getPassword())); // 執行登入. currentUser.login(token); } // ... catch more exceptions here (maybe custom ones specific to your application? // 所有認證時異常的父類. catch (AuthenticationException ae) { //unexpected condition? error? System.out.println("login failed :" + ae.getMessage()); } } return "redirect:/index.jsp"; }
在這裡列印了所有的UsernamePasswordToken的屬性值
再在對應的Realm中列印一下接收的AuthenticationToken的所有屬性值
一個簡單的例子:
public class ShiroRealm extends AuthenticatingRealm { @Resource private AdminService adminService; @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.out.println("AuthenticationToken:"); System.out.println("hashCode:" + authenticationToken.hashCode()); System.out.println("Principal:" + authenticationToken.getPrincipal()); System.out.println("Credentials:" + authenticationToken.getCredentials().toString()); return null; } }
列印結果:
注意:
credentials這個屬性,在UsernamePasswordToken中其實是個Object,檢視原始碼,getCredentials()方法返回的就是password
原始碼,見圖:
故,若要正確得到UsernamePasswordToken的password,可以將credentials轉為char[]再String.valof()方法獲得String。