`
qq543123909
  • 浏览: 25288 次
社区版块
存档分类
最新评论

Spring Security 学习(6)

阅读更多

这篇主要的内容是:

自定义用户表和权限表

也是解决第三篇留下的问题,这个解决方案是在这个大哥的博客看到的http://downpour.iteye.com/blog/319965

下面就是我自己做的例子:

 

准备工作:

1.在数据库中 自定义我们的用户表 和 权限表.

-- 用户表 
create table tb_users(
      id number primary key not null,
      c_username nvarchar2(50) not null,
      c_password nvarchar2(50) not null,
      c_enabled char(1) not null
);

--权限表
create table tb_role(
       id number primary key not null,
       c_authority nvarchar2(50) not null
);

--用户权限中间表
create table tb_user_role(
      id number primary key not null,
      c_user_id number not null,
      c_role_id number not null
);

--添加相应的外键引用 和 索引
alter table tb_user_role 
add constraint fk_user_id foreign key (c_user_id) references tb_users(id);

alter table tb_user_role 
add constraint fk_role_id foreign key(c_role_id) references tb_role(id);  

alter table tb_users
add constraint uq_username unique(c_username);

create unique index ix_user_role on tb_user_role (c_user_id,c_role_id);


--插入测试数据.
insert into tb_users values(1,'user','ee11cbb19052e40b07aac0ca060c23ee','1');
insert into tb_users values(2,'admin','21232f297a57a5a743894a0e4a801fc3','1');
insert into tb_users values(3,'zyk','a90157d9f9a8d683152ca521cf1ecfac','1');

select * from users

insert into tb_role values(1,'ROLE_ADMIN');
insert into tb_role values(2,'ROLE_USER');

select * from tb_role

insert into tb_user_role values(1,1,2);
insert into tb_user_role values(2,2,1);
insert into tb_user_role values(3,3,1);
insert into tb_user_role values(4,3,2);

select * from tb_user_role



 

上面的用户名 和 密码 都是一样的 例如用户名  user  对应的 密码是 user  经过MD5 处理出来后的字串

是ee11cbb19052e40b07aac0ca060c23ee 保存在数据库 出于安全性的考虑.

 

2.配置applicationCotext.xml

	<!--配置认证管理器 -->
	<security:authentication-manager>
		<security:authentication-provider>
			<security:password-encoder hash="md5" />
			<security:jdbc-user-service
				data-source-ref="dataSource" 
				 users-by-username-query="select u.c_username username,u.c_password password,u.c_enabled enabled 
				 from tb_users u where u.c_username=? "
				authorities-by-username-query="select u.c_username username,r.c_authority authority 
				from tb_users u , tb_role r ,tb_user_role ur 
				where u.id=ur.c_user_id  and r.id=ur.c_role_id and u.c_username=?" />
			<!-- <security:user-service> -->
			<!-- <security:user name="user" password="user" -->
			<!-- authorities="ROLE_USER" /> -->
			<!-- </security:user-service> -->
		</security:authentication-provider>
	</security:authentication-manager>

 

 

到此 使用 用户名 zyk 密码 zyk 进行登录成功 .测试Ok. 

 

 

通过添加users-by-username-query 和authorities-by-username-query 属性,我们可

以使用你自己的SQL 覆盖默认的SQL 语句。这样我们就可以指定查询的是我们自己定义的表了

但是 我们必须确保我们的SQL 语句返回的列与Spring Security 所期待的一样  

 

很显然的是 用户表 需要的 字段是 username , password,enabled .

权限表 则是 username ,authority

共同的是 他们都需要 username 作为where子句的限制条件. 

 

 

 

 

 

 

 

 

 

 

1
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics