import com.sun.org.apache.bcel.internal.util.ClassPath;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniFactorySupport;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
public class myshiro {
public static void main(String[] args) {
// 创建安全管理器工厂
Factory<SecurityManager> securityManagerFactory=new IniSecurityManagerFactory("classpath:shiro.ini");
// 创建安全管理器
SecurityManager securityManager=securityManagerFactory.getInstance();
// 设置为当前运行环境
SecurityUtils.setSecurityManager(securityManager);
// 创建subject主体
Subject subject= SecurityUtils.getSubject();
// 提交认证前创建令牌
UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken("zhangsan","1234");
// 提交认证
try {
subject.login(usernamePasswordToken);
boolean boo=subject.hasRole("role1");
if (boo){
System.out.println("它是老大");
}
if(subject.isPermitted("user:add")){
System.out.println("它有展示的权利");
}
if (subject.isAuthenticated()){
System.out.println("ok");
}else{
System.out.println("no");
}
} catch (AuthenticationException e) {
e.printStackTrace();
}
}
}
[users]
zhangsan=1234,role1,role2
[roles]
role1=user:update,user:add
role2=user:list
//自定义realm授权,当你在自定义中的realm中有认证的时候就不需要在ini配置文件中在此配置
//获取授权信息
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
String userName=principalCollection.getPrimaryPrincipal().toString();
List<String> permission=new ArrayList<String>();
permission.add("user:add");
permission.add("user:list");
permission.add("user:update");
SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
for (String s : permission) {
info.addStringPermission(s);
}
return info;
}
}
[main]
userRealm=UserRealm
securityManager.realm=$userRealm
网友评论