shiro的java环境搭建
shiro初体验
eclipse创建工程shiro-demo的工程,将为工程添加maven环境。
步骤如下:
1、导入maven依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
</dependency>
2、src下创建shiro需要的ini文件
创建shiro.ini,配置如下:
[users]代表用户
例:
root=123456,admin
root是用户,123456为密码,admin代表root拥有的角色
[roles]代表角色
例:
admin=*代表admin拥有所有权限
test=search,add,update代表test角色拥有search权限等
[users]
root=123456,admin
koby=koby,test
[roles]
admin=*
test=search,add,update
3、shiro代码
创建ShiroTest类,代码如下:
创建SecurityManager的工厂类IniSecurityManagerFactory,通过工厂类获取SecurityManager实例;
SecurityUtils设置SecurityManager并获取Subject实例(即主体);
创建用户身份实例UsernamePasswordToken;
subject.login(token)进行登录;
subject.hasRole检查用户是否拥有某角色;
subject.isPermitted检查用户是否拥有某权限
subject.isAuthenticated检查用户是否认证
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
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 ShiroTest {
public static void main(String[] args) {
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("koby","koby");
System.out.println(subject.isAuthenticated());
try {
subject.login(token);
if(subject.isAuthenticated()){
System.out.println("登录成功");
if(subject.hasRole("admin")){
System.out.println("拥有admin角色");
}else{
System.out.println("拥有普通用户角色");
}
if(subject.isPermitted("search")){
System.out.println("拥有搜索权限");
}else{
System.out.println("没有搜索权限");
}
if(subject.isPermitted("search")){
System.out.println("拥有搜索权限");
}else{
System.out.println("没有搜索权限");
}
}
} catch (AuthenticationException e) {
// e.printStackTrace();
System.out.println("用户名或密码错误");
}
System.out.println(subject.isAuthenticated());
}
}