编写shiro-permission-realm.ini配置文件
[main]
#声明一个realm
myReal= com.feng.realm.PermissionRealm
#指定securityManager的realms实现
securityManager.realms=$myReal
自定义Realm,重写授权方法
public class PermissionRealm extends AuthorizingRealm {
public String getName(){
return "PermissionRealm";
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
String username = (String) principalCollection.getPrimaryPrincipal();
List<String> roles = new ArrayList<>();
List<String> permission = new ArrayList<>();
roles.add("role1");
permission.add("user:*");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addRoles(roles);
info.addStringPermissions(permission);
return info;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String)token.getPrincipal();
if (!"zhangsan".equals(username)){
return null;
}
String password="666";
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password, getName());
return info;
}
编写测试程序
public class MyTest {
@Test
public void hasRole(){
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-permission-realm.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "666");
try {
subject.login(token);
}catch (Exception e){
e.printStackTrace();
}
System.out.println(subject.hasRole("role1"));
System.out.println(subject.isPermitted("user:delete"));
}
}