shiro學習筆記(3)--自定義realm、授權
阿新 • • 發佈:2018-11-14
一:自定義Realm
1、繼承AuthorizingRealm(因為該類中有認證、授權的抽象方法,實現簡單)
public class MyRealm1 extends AuthorizingRealm{ @Override public String getName() { return "myrealm"; } protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { //使用者輸入資訊 String username = (String) token.getPrincipal(); System.out.println(username); //模擬從庫裡查詢對應使用者證明資訊 String pwd = "123654"; SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username,pwd,getName()); return simpleAuthenticationInfo; } protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { return null; } }
2、main方法
public static void main(String[] args) { Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro/shiro-realm.ini"); SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); Subject subject = SecurityUtils.getSubject(); //認證 UsernamePasswordToken token = new UsernamePasswordToken("kexq","123654"); subject.login(token); if(subject.isAuthenticated()){ System.out.println("認證成功!"); } }
3、ini配置
#shiro簡單配置例項
#主配置
[main]
#使用者資訊配置
[users]
kexq=123654
ke=123654
#配置自定義realm
myrealm=com.kexq.common.shiro.realm.MyRealm
securityManager.realm=$myrealm
二:授權
說明:ini配置或自定義realm配置
1、ini配置
配置規範參考https://www.w3cschool.cn/shiro/xgj31if4.html
#shiro簡單配置例項 #主配置 [main] #使用者資訊配置 [users] kexq=123654,role1,role5 ke=123654,role1,role3,role4 #角色資訊配置 [roles] admin=* role1=sys:edit,sys:view #縮寫時需要引號 role2="sys:view,update" role3=sys:* role4=:* role5=sys:edit:1
subject的驗證方法
(1)subject().hasRole*()
(2)subject().checkRole*() 驗證失敗丟擲異常
(3)subject().isPermitted*()
(4)subject().checkPermission*() 驗證失敗丟擲異常
驗證失敗丟擲異常AuthenticationException及其子類異常
subject.login(usernamePasswordToken);
if(subject.isAuthenticated()){
System.out.println("認證成功");
boolean flage1 = subject.isPermitted("sys:edit:1"); //sys資源view許可權
boolean flage2 = subject.isPermitted("sys:*"); //sys資源所有許可權
boolean flage3 = subject.isPermitted(":*"); //所有資源所有許可權
System.out.println(flage1);
System.out.println(flage2);
System.out.println(flage3);
boolean flage4 = subject.isPermittedAll("sys:view","sys:delete"); //一次檢測多個資源
System.out.println(flage4);
}else{
System.out.println("認證失敗");
}
2、自定義realm配置
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
String name = (String)principalCollection.getPrimaryPrincipal();
//模擬從庫裡提取使用者許可權
List<String> list = new ArrayList<String>();
list.add("user:view");
list.add("user:add");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addStringPermissions(list);
return info;
}