上一節介紹了realm的作用:
realm:需要根據token中的身份信息去查詢數據庫(入門程序使用ini配置文件),如果查到用戶返回認證信息,如果查詢不到返回null。token就相當於是對用戶輸入的用戶名和密碼的一個封裝。下面就是創建一個用戶名密碼token:
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "111111");
Realm結構:
自定義realm
package cn.qlq.realm; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; /** * 自定義realm。根據上面穿下來的token去數據庫查信息,查到返回一個SimpleAuthenticationInfo,查不到返回null * @author: qlq * @date : 2017年7月28日下午8:45:52 */ public class CustomRealm extends AuthorizingRealm { // 設置realm的名稱 @Override public void setName(String name) { super.setName("customRealm"); } // 用於認證 @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken token) throws AuthenticationException { // token是用戶輸入的 // 第一步從token中取出身份信息(token代表用戶輸入的傳下來的信息) String userCode = (String) token.getPrincipal(); // 第二步:根據用戶輸入的userCode從數據庫查詢 // ....從數據庫查數據 // 如果查詢不到返回null //數據庫中用戶賬號是zhangsansan /*if(!userCode.equals("zhangsansan")){// return null; }*/ // 模擬從數據庫查詢到密碼 String password = "111111"; // 如果查詢到返回認證信息AuthenticationInfo SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo( userCode, password, this.getName()); return simpleAuthenticationInfo; } // 用於授權 @Override protected AuthorizationInfo doGetAuthorizationInfo( PrincipalCollection principals) { // TODO Auto-generated method stub return null; } }
查看:AuthenticationToken
public interface AuthenticationToken extends Serializable { Object getPrincipal();//用戶輸入的用戶名 Object getCredentials();//用戶輸入的密碼 }
配置realm
需要在shiro-realm.ini配置realm注入到securityManager中。
Java測試:
// 自定義realm測試 @Test public void testCustomRealm() { // 創建securityManager工廠,通過ini配置文件創建securityManager工廠 Factory<SecurityManager> factory = new IniSecurityManagerFactory( "classpath:shiro-realm.ini"); // 創建SecurityManager SecurityManager securityManager = factory.getInstance(); // 將securityManager設置當前的運行環境中 SecurityUtils.setSecurityManager(securityManager); // 從SecurityUtils裏邊創建一個subject Subject subject = SecurityUtils.getSubject(); // 在認證提交前準備token(令牌) // 這裏的賬號和密碼 將來是由用戶輸入進去 UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "111111"); try { // 執行認證提交 subject.login(token); } catch (AuthenticationException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 是否認證通過 boolean isAuthenticated = subject.isAuthenticated(); System.out.println("是否認證通過:" + isAuthenticated); }