Realm:
在實際應用中,shiro從數據庫中獲取安全數據(如用戶、角色、權限),而不是從ini中,可作為安全數據源
即SecurityManager要驗證用戶身份,那么它需要從Realm獲取相應的用戶進行比較以確定用戶身份是否合法
也需要從Realm中得到用戶相應的角色/權限以確定用戶是否能進行操作
org.apache.shiro.realm.Realm:
String getName(); //返回一個唯一的Realm名字 boolean supports(AuthenticationToken token); //判斷此Realm是否支持此Token AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException; //根據Token獲取認證信息
1 自定義Realm:
一般實現AuthorizingRealm(授權)接口即可,此接口繼承了AuthenticatingRealm(身份驗證),也簡介集成了CachingRealm(緩存)接口
ini配置指定自定義Realm
[main] #自定義realm customRealm=com.roxy.shiro.realm.CustomRealm #指定secrityManager的Realm實現 securityManager.realm=$customRealm
realm:
public class CustomRealm extends AuthenticatingRealm{ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // 從數據庫獲取用戶名和密碼 String username = "draco"; String password = "615"; //從用戶的輸入中生成token,拿到用戶名密碼 String inputUsername = (String)token.getPrincipal(); if(!inputUsername.equals(username)){ throw new UnknownAccountException("用戶不存在"); } /* if(status == 0){ throw new LockedAccountException("用戶被鎖定"); }*/ String inputPassword = (String)token.getCredentials(); if(!inputPassword.equals(password)){ throw new IncorrectCredentialsException("密碼不正確"); } System.out.println(this.getName()); String realName = this.getName();
//拿到授權信息 SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(inputUsername, inputPassword, realName); return info; } }
測試出現錯誤:
錯誤信息提示類型轉換錯誤,猜測username或者password的類型轉換出錯,但是日志已經將username打印出來,所以password轉換出錯
2017-10-14 20:24:34,680 WARN [org.apache.shiro.authc.AbstractAuthenticator] -
Authentication failed for token submission [org.apache.shiro.authc.UsernamePasswordToken - draco, rememberMe=false].
Possible unexpected error? (Typical or expected login exceptions should extend from AuthenticationException). java.lang.ClassCastException: [C cannot be cast to java.lang.String
將代碼改為:
String inputPassword = new String((char[])token.getCredentials());
再次測試:
2017-10-14 20:28:41,793 DEBUG [com.roxy.shiro.quickstart.Quickstart] - 密碼錯誤 2017-10-14 20:28:41,794 DEBUG [com.roxy.shiro.quickstart.Quickstart] - 是否登陸成功:false
2 多Realm配置:
[main] #自定義realm customRealm=com.roxy.shiro.realm.CustomRealm
customRealm2=com.roxy.shiro.realm.CustomRealm2
#指定secrityManager的Realm實現 (可選,若不指定,按照聲明的順序進行使用)
securityManager.realm=$customRealm,$customRealm2
SecurityManager會按照Realms指定的順序進行身份驗證
如果Realm沒有被顯示的指定,則會被忽略