概述
自定义Realm的数据库表
用户表
create table tb_users(
id int(11) primary key auto_increment,
username varchar(60) not null,
password varchar(60) not null,
salt varchar(100) null default null
);
insert into tb_users(username,password) values('zhangsan','e10adc3949ba59abbe56e057f20f883e');
insert into tb_users(username,password) values('lisi','e10adc3949ba59abbe56e057f20f883e');
insert into tb_users(username,password) values('wangwu','e10adc3949ba59abbe56e057f20f883e');
insert into tb_users(username,password) values('zhaoliu','e10adc3949ba59abbe56e057f20f883e');
insert into tb_users(username,password) values('chenqi','e10adc3949ba59abbe56e057f20f883e');
insert into tb_users(username,password) values('erha','e10adc3949ba59abbe56e057f20f883e');
insert into tb_users(username,password) values('laowang','e10adc3949ba59abbe56e057f20f883e');
角色表
create table tb_roles(
roleId int(11) primary key auto_increment,
rolename varchar(60) not null
);
insert into tb_roles (rolename) values ('manager');
insert into tb_roles (rolename) values ('user');
insert into tb_roles (rolename) values ('mmanager');
insert into tb_roles (rolename) values ('xmanager');
insert into tb_roles (rolename) values ('cmanager');
权限表
create table tb_permissions(
perId int(11) primary key auto_increment,
perCode varchar(60) not null,
perName varchar(60)
);
insert into tb_permissions(perCode) values('sys:m:find');
insert into tb_permissions(perCode) values('sys:m:save');
insert into tb_permissions(perCode) values('sys:m:delete');
insert into tb_permissions(perCode) values('sys:m:update');
insert into tb_permissions(perCode) values('sys:c:find');
insert into tb_permissions(perCode) values('sys:c:save');
insert into tb_permissions(perCode) values('sys:c:delete');
insert into tb_permissions(perCode) values('sys:c:update');
insert into tb_permissions(perCode) values('sys:x:find');
insert into tb_permissions(perCode) values('sys:x:save');
insert into tb_permissions(perCode) values('sys:x:delete');
insert into tb_permissions(perCode) values('sys:x:update');
角色权限表
create table tb_rps(
rid int not null,
pid int not null
);
insert into tb_rps values(1,1);
insert into tb_rps values(1,2);
insert into tb_rps values(1,3);
insert into tb_rps values(1,4);
insert into tb_rps values(1,5);
insert into tb_rps values(1,6);
insert into tb_rps values(1,7);
insert into tb_rps values(1,8);
insert into tb_rps values(1,9);
insert into tb_rps values(1,10);
insert into tb_rps values(1,11);
insert into tb_rps values(1,12);
insert into tb_rps values(2,1);
insert into tb_rps values(2,5);
insert into tb_rps values(2,9);
insert into tb_rps values(3,1);
insert into tb_rps values(3,2);
insert into tb_rps values(3,3);
insert into tb_rps values(3,4);
insert into tb_rps values(4,9);
insert into tb_rps values(4,10);
insert into tb_rps values(4,11);
insert into tb_rps values(4,12);
insert into tb_rps values(5,5);
insert into tb_rps values(5,6);
insert into tb_rps values(5,7);
insert into tb_rps values(5,8);
角色用户表
create table tb_urs(
uid int not null,
rid int not null
);
insert into tb_urs values (1,1);
insert into tb_urs values (2,2);
insert into tb_urs values (3,2);
insert into tb_urs values (4,3);
insert into tb_urs values (5,4);
insert into tb_urs values (6,3);
insert into tb_urs values (6,4);
insert into tb_urs values (7,5);
sql脚本
-- 根据用户名查询用户角色信息 --
-- 第一种脚本不清晰 --
SELECT *
FROM tb_users u INNER JOIN tb_roles r INNER JOIN tb_urs ur
ON u.id = ur.uid and r.roleId = ur.rid
WHERE u.username ="zhangsan";
-- 第二种非常清晰 --
SELECT r.rolename
FROM tb_users u INNER JOIN tb_urs ur
ON u.id = ur.uid INNER JOIN tb_roles r
ON ur.rid = r.roleId
WHERE u.username ="lisi";
-- 根据用户名查询用户的权限列表 --
SELECT p.perCode
FROM tb_users u INNER JOIN tb_urs ur
ON u.id = ur.uid INNER JOIN tb_roles r
ON ur.rid = r.roleId INNER JOIN tb_rps rp
ON r.roleId = rp.rid INNER JOIN tb_permissions p
ON rp.pid = p.perId
WHERE u.username ="zhangsan";
导入jar包
<dependencies>
<!--shiro依赖开始-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.1</version>
</dependency>
<!--shiro依赖结束-->
<!--commons-logging-->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!--spring-context(spring-core,spring-beans,spring-aop,spring-expression)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--aspectjweaver-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.20</version>
</dependency>
<!--Junit依赖的jar包-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--Spring整合测试依赖的jar包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.9.RELEASE</version>
<scope>test</scope>
</dependency>
<!--mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!-- mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!-- spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--SpringMVC依赖的jar包 start-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--SpringMVC依赖的jar包 end-->
</dependencies>
XML配置文件
- spring-context.xml
- spring-context-druid.xml
- spring-context-mybatis.xml
- spring-context-tx.xml
- spring-context-mvc.xml
- spring-context-shiro.xml
spring-context.xml spring-context-druid.xml spring-context-mybatis.xml spring-context-tx.xml spring-context-mvc.xml的配置和SSM中的配置是一样的
spring-context-shiro.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--shiro过滤器-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"></property>
<!--配置登录页面地址,非必须,默认寻找web项目根路径下的/login.jsp-->
<property name="loginUrl" value="/login.jsp"></property>
<!--配置登录成功之后跳转的页面路径,此配置一般不使用,一般在LoginController中处理逻辑
<property name="successUrl" value="/index.jsp"></property>
-->
<!--权限不足时跳转的页面-->
<property name="unauthorizedUrl" value="/permission.jsp"></property>
<!--配置拦截规则-->
<property name="filterChainDefinitions">
<value>
/index.jsp=authc
/**=anon
</value>
</property>
</bean>
<!--生命周期管理器是shiro内部工作所需要的配置-->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"></bean>
<!--证书匹配器-->
<!-- <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.Md5CredentialsMatcher"></bean>-->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>
<!--声明注解配置-->
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
<!--缓存管理-->
<bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager"></bean>
<!--shiro安全管理器-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myRealm"></property>
<property name="cacheManager" ref="cacheManager"></property>
</bean>
<!--配置自级的Realm的bean-->
<!--<bean id="myRealm" class="com.xzq.shiro.utils.MyRealm">
<property name="userDAO" ref="userDAO"/>
</bean> -->
<!--使用自带的Realm-->
<!--<bean id="jdbcRealm" class="org.apache.shiro.realm.jdbc.JdbcRealm">
<property name="credentialsMatcher" ref="credentialsMatcher"></property>
<property name="permissionsLookupEnabled" value="true"></property>
<property name="dataSource" ref="dataSource"></property>
</bean> -->
</beans>
</beans>
myRealm类
/**
*这里是用注解的方式将myRealm交给spring进行管理
*/
@Component
public class MyRealm extends AuthorizingRealm {
@Autowired
private UserDAO userDAO;
@Autowired
private RoleDAO roleDAO;
@Autowired
private PermissionDAO permissionDAO;
@Override
public String getName() {
return "myRealm";
}
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
User user = (User) principalCollection.iterator().next();
int userId = user.getId();
Set<String> roles= roleDAO.findRoleByUserId(userId);
Set<String> permissions = permissionDAO.findPermissionByuserId(userId);
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
authorizationInfo.setRoles(roles);
authorizationInfo.setStringPermissions(permissions);
return authorizationInfo;
}
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
String username = token.getUsername();
String password = new String(token.getPassword());
String md5Pwd = new SimpleHash("MD5",password).toHex();
User user = userDAO.findUserByUsername(username);
if(user == null){
throw new UnknownAccountException("账号不存在");
}else {
if (!user.getPassword().equals(md5Pwd)){
throw new IncorrectCredentialsException("密码错误");
}
}
return new SimpleAuthenticationInfo(user,password,getName());
}
}
登录验证
dao类
@MapperScan
@Repository
public interface UserDAO {
@Select("select * from tb_users where username=#{username}")
public User findUserByUsername(String username);
}
service类
@Service
public class UserService {
public void login(String userName,String userPwd) throws Exception{
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(userName,userPwd);
subject.login(token);
}
}
Controller类
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/login.do")
public String login(String userName, String userPwd, Model model){
try{
userService.login(userName,userPwd);
return "/index.jsp";
}catch (Exception e){
model.addAttribute("tips","登录验证失败,请重试!");
return "/login.jsp";
}
}
}
授权管理
查询用户的角色
@MapperScan
@Repository
public interface RoleDAO {
@Select("SELECT r.rolename FROM tb_users u INNER JOIN tb_urs ur ON u.id = ur.uid INNER JOIN tb_roles r ON ur.rid = r.roleId WHERE u.id =#{userId}")
public Set<String> findRoleByUserId(Integer userId);
}
查询用户的权限
@MapperScan
@Repository
public interface PermissionDAO {
@Select("SELECT p.perCode FROM tb_users u INNER JOIN tb_urs ur ON u.id = ur.uid INNER JOIN tb_roles r ON ur.rid = r.roleId INNER JOIN tb_rps rp ON r.roleId = rp.rid INNER JOIN tb_permissions p ON rp.pid = p.perId WHERE u.id =#{userId};")
public Set<String> findPermissionByuserId(Integer userId);
}
然后就是在myRealm中查询出这个用户的Role和Permission的Set集合 将这连个集合封装在
SimpleAuthorizationInfo中
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
User user = (User) principalCollection.iterator().next();
int userId = user.getId();
Set<String> roles= roleDAO.findRoleByUserId(userId);
Set<String> permissions = permissionDAO.findPermissionByuserId(userId);
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
authorizationInfo.setRoles(roles);
authorizationInfo.setStringPermissions(permissions);
return authorizationInfo;
}
通过注解来配置Controller中的每个方法需要的权限
@Controller
@RequestMapping("/m")
public class MController {
@RequestMapping("/save.do")
@RequiresPermissions("sys:m:save")
public String save(){
System.out.println("-------save");
return "/index.jsp";
}
@RequestMapping("/delete.do")
@RequiresPermissions("sys:m:delete")
public String delete(){
System.out.println("-------delete");
return "/index.jsp";
}
@RequestMapping("/update.do")
@RequiresPermissions("sys:m:update")
public String update(){
System.out.println("-------update");
return "/index.jsp";
}
@RequestMapping("/select.do")
@RequiresPermissions("sys:m:find")
public String select(){
System.out.println("-------select");
return "/index.jsp";
}
}
最后
以上就是甜美彩虹为你收集整理的SSM框架整合shiro框架的全部内容,希望文章能够帮你解决SSM框架整合shiro框架所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复