這里以簡單的登陸為例子
控制器對應的登陸方法:
@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。