本章讲解一下如何使用Shiro+oracle实现用户授权。所谓授权,就是判断当前用户具体哪些权限,能够执行哪些操作,或是访问哪些资源(Web中的URL,又或是页面上的一个按钮,一个编辑框等都可以视为资源)。因此我们需要数据表来存储这些资源信息,以及用户、角色和资源的分配关系。上文中已经创建了用户表,在本文中我们需要再创始角色表、资源表,以及用户和角色、角色和资源之间的关系表。这里仅为了需要让测试程序跑通,所以字段都很简单,在使用中可根据实际情况对字段进行增加。
一、建表
--1、已经创建好的用户表
CREATETABLEsec_user(
user_id number(10)primarykey,
user_name varchar2(64),
passwordvarchar2(128),
created_time date ,
update_time timestamp
) ;
select *from sec_user;
--2、创建角色表、
CREATETABLE sec_role (
role_id number(10)primarykey,
role_name varchar2(64),
created_time date,
update_time date
)
select *from sec_role ;
dropsequence role_seq;
createsequence role_seq;
deletefrom sec_role ;
insertinto sec_rolevalues(role_seq.nextval,'admin','2-2月-12','2-2月-12');
select *from sec_role;
--3、权限表
CREATETABLE sec_permission(
permission_id number(10)primarykey,
permission_name varchar2(64),
created_time date ,
update_time date
);
createsequence permission_seq;
insertinto sec_permissionvalues(permission_seq.nextval,'manager','2-2月-12','2-2月-12');
insertinto sec_permissionvalues(permission_seq.nextval,'create_user1','2-2月-12','2-2月-12');
select *from sec_permission;
--4、用户和角色的关系表
CREATETABLE sec_user_role(
idnumber(10)primarykey,
user_id number(10),
role_id number(10)
)
createsequence user_role_seq;
insertinto sec_user_rolevalues(user_role_seq.nextval,1,1);
insertinto sec_user_rolevalues(user_role_seq.nextval,2,1);
insertinto sec_user_rolevalues(user_role_seq.nextval,3,1);
select *from sec_user_role;
--5、角色和权限的关系表
CREATETABLE sec_role_permission(
idnumber(10)primarykey,
permission_id number(10),
role_id number(10)
)
createsequencerole_permission_seq;
insertinto sec_role_permissionvalues(role_permission_seq.nextval,1,1);
insertinto sec_role_permissionvalues(role_permission_seq.nextval,1,2);
insertinto sec_role_permissionvalues(role_permission_seq.nextval,1,3);
insertinto sec_role_permissionvalues(role_permission_seq.nextval,2,1);
select *fromsec_role_permission;
--根据用户名查询角色
SELECTrole_name
from sec_user_role
leftjoin sec_roleusing(role_id)
leftjoin sec_userusing(user_id)
WHERE user_name ='ammin'
--根据角色名查询权限
SELECTpermission_name
FROMsec_role_permission
leftjoin sec_roleusing(role_id)
leftjoin sec_permissionusing(permission_id)
whererole_name='admin';
二、项目架构
三、加载依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>10.2.0.4.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.0.13</version>
<scope>runtime</scope>
</dependency>
四、shiro.ini
建好表之后,我们就需要为JdbcRealm对象指定用户、角色和权限的查询语句
[main]
dataSource=org.springframework.jdbc.datasource.DriverManagerDataSource
dataSource.driverClassName=oracle.jdbc.driver.OracleDriver
dataSource.url=jdbc:oracle:thin:@localhost:1521:orcl
dataSource.username=system
dataSource.password=orcl
jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled =true
jdbcRealm.dataSource=$dataSource
#用户认证(登录)查询语句,以用户名为查询条件
jdbcRealm.authenticationQuery = SELECTpassword FROM sec_user WHERE user_name = ?
#用户角色查询语句,以用户名为查询条件,判断用户是否拥有某个角色
jdbcRealm.userRolesQuery = SELECT role_namefrom sec_user_role left join sec_role using(role_id) left join sec_userusing(user_id) WHERE user_name =?
#资源许可查询语句,以角色名称为查询条件,判断角色是否拥有某个资源的许可
jdbcRealm.permissionsQuery= SELECT permission_name FROM sec_role_permission left join sec_roleusing(role_id) left join sec_permission using(permission_id) where role_name=?
关于这三条查询语句,大家注意:
· 用户认证的查询语句中,只需要以用户名为查询条件,查询出密码字段即可,如果您在select后面使用了星号(*)或是查询字段多于一个,都无法通过用户认证。
· 用户角色查询语句,以用户名为查询条件,通过多表关联,查询出角色名字段即可,不可使用星号,或多个字段
· 资源许可查询语句,以角色名为查询条件,通过多表关联,查询出资源名称字段即可,不可使用星号,或多个字段
五、测试源代码
package cn.com.bochy.test;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.apache.shiro.mgt.SecurityManager;
public class TestShiroDB extends AuthorizingRealm{
public static void main(String[] args) {
// 1.获取SecurityManager工厂,此处使用ini配置文件初始化SecurityManager
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
// 2.获取SecurityManager实例,并绑定到SecurityUtils
SecurityManager sm = factory.getInstance();
SecurityUtils.setSecurityManager(sm);
// 3.得到Subject
Subject subject =SecurityUtils.getSubject();
// 4.创建用户登录凭证
UsernamePasswordToken token= new UsernamePasswordToken("ammin","123456");
token.setRememberMe(true);
// 5.登录,如果登录失败会抛出不同的异常,根据异常输出失败原因
try {
subject.login(token);
// 6.判断是否成功登录
if(subject.isAuthenticated())
System.out.println("登录成功!!");
// 判断用户是否拥有某个角色
if(subject.hasRole("admin")){
System.out.println("admin角色");
}
// 使用Shiro自带的断言判断用户是否有被授权
//subject.checkRole("manager");
subject.checkRole("admin");
subject.checkPermission("create_user");
// 7.注销用户
subject.logout();
} catch (IncorrectCredentialsException e) {
System.out.println("登录密码错误. Password for account " + token.getPrincipal() +" was incorrect.");
} catch (ExcessiveAttemptsException e) {
System.out.println("登录失败次数过多");
} catch (LockedAccountException e) {
System.out.println("帐号已被锁定. The account for username " + token.getPrincipal() +" was locked.");
} catch (DisabledAccountException e) {
System.out.println("帐号已被禁用. The account for username " + token.getPrincipal() +" was disabled.");
} catch (ExpiredCredentialsException e) {
System.out.println("帐号已过期. the account for username " + token.getPrincipal() +" was expired.");
} catch (UnknownAccountException e) {
System.out.println("帐号不存在. There is no user with username of" +token.getPrincipal());
} catch (UnauthorizedException e) {
System.out.println("您没有得到相应的授权!" + e.getMessage());
}
}
@Override
protected AuthorizationInfodoGetAuthorizationInfo(PrincipalCollection arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
protected AuthenticationInfodoGetAuthenticationInfo(
AuthenticationToken arg0) throws AuthenticationException {
// TODO Auto-generated method stub
return null;
}
}
六、测试结果
登录成功!!
07:01:25.481 [main] DEBUG o.a.shiro.realm.AuthorizingRealm - NoauthorizationCache instance set. Checking for a cacheManager...
07:01:25.481 [main] DEBUG o.a.shiro.realm.AuthorizingRealm - No cache orcacheManager properties have been set. Authorization cache cannot be obtained.
07:01:25.481 [main] DEBUG o.s.j.d.DriverManagerDataSource - Creating newJDBC DriverManager Connection to [jdbc:oracle:thin:@localhost:1521:orcl]
admin角色
07:01:25.512 [main] DEBUG o.a.shiro.realm.AuthorizingRealm - NoauthorizationCache instance set. Checkingfor a cacheManager...
07:01:25.512 [main] DEBUG o.a.shiro.realm.AuthorizingRealm - No cache orcacheManager properties have been set. Authorization cache cannot be obtained.
07:01:25.513 [main] DEBUG o.s.j.d.DriverManagerDataSource - Creating newJDBC DriverManager Connection to [jdbc:oracle:thin:@localhost:1521:orcl]
07:01:25.529 [main] DEBUG o.a.shiro.realm.AuthorizingRealm - NoauthorizationCache instance set. Checking for a cacheManager...
07:01:25.529 [main] DEBUG o.a.shiro.realm.AuthorizingRealm - No cache orcacheManager properties have been set. Authorization cache cannot be obtained.
07:01:25.529 [main] DEBUG o.s.j.d.DriverManagerDataSource - Creating newJDBC DriverManager Connection to [jdbc:oracle:thin:@localhost:1521:orcl]
您得到相应的create_user1授权!
532



被折叠的 条评论
为什么被折叠?



