SpringMVC集成shrio框架
使用SHIRO的步骤:
1,导入jar
2,配置web.xml
3,建立dbRelm
4,在Spring中配置
添加所需jar包:
- <!--Apache Shiro所需的jar包-->
- <dependency>
- <groupId>org.apache.shiro</groupId>
- <artifactId>shiro-core</artifactId>
- <version>1.2.2</version>
- </dependency>
- <dependency>
- <groupId>org.apache.shiro</groupId>
- <artifactId>shiro-web</artifactId>
- <version>1.2.2</version>
- </dependency>
- <dependency>
- <groupId>org.apache.shiro</groupId>
- <artifactId>shiro-spring</artifactId>
- <version>1.2.2</version>
- </dependency>
- </dependencies>
web.xml中配置shrio的过滤器:
- <!-- Shiro配置 -->
- <filter>
- <filter-name>shiroFilter</filter-name>
- <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>shiroFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
权限控制类:
public class ShiroRealm extends AuthorizingRealm { private static final Logger log = Logger.getLogger(ShiroRealm.class); @Autowired
private SysUsersService userService;
@Autowired
private SysUserRolesService userRoleService;
@Autowired
private SysRolePermissionsService sysRolePermissionsService;
@Autowired
private SysPermissionsService sysPermissionsService; /**
* 为当前登录的Subject授予角色和权限
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { // 获取当前登录的用户名,等价于(String)principals.fromRealm(this.getName()).iterator().next()
String currentUsername = (String) super.getAvailablePrincipal(principals);
List<String> roleList = new ArrayList<String>();
List<String> permissionList = new ArrayList<String>();
// 从数据库中获取当前登录用户的详细信息
// roleList.add("admin"); SysUsers user = userService.getUserByUsername(currentUsername);
if(null != user){
//超级用户直接获取所有权限
if(user.getIsAdministrator()==1){
List<SysPermissions> pList = sysPermissionsService.getAll();
if(pList!=null && pList.size()>0){
for (SysPermissions p: pList) {
permissionList.add(p.getPermissionKey());
}
}
}else {
//获取用户角色列表
List<SysUserRoles> roles = userRoleService.getUserRolesByUserName(currentUsername);
List<Integer> roleIdList = new ArrayList<>();
if (roles != null&&roles.size()>0) {
for (SysUserRoles role : roles) {
System.out.println(role.getRoleKey());
log.debug("授予角色>>>" + role.getRoleKey());
roleList.add(role.getRoleKey());
roleIdList.add(role.getRoleId());
}
}
//获取用户权限列表
List<SysRolePermissions> permissionsList = sysRolePermissionsService.getPermissionsByRoleIds(roleIdList);
if (permissionsList != null && permissionsList.size() > 0) {
for (SysRolePermissions pmss : permissionsList) {
if (!StringUtils.isBlank(pmss.getPermissionKey())) {
log.debug("授予权限>>>>" + pmss.getPermissionKey());
permissionList.add(pmss.getPermissionKey());
}
}
}
} }else {
throw new AuthorizationException();
} // if (null != user) {
// // 实体类User中包含有用户角色的实体类信息
// if (null != user.getRoles() && user.getRoles().size() > 0) {
// // 获取当前登录用户的角色
// for (Role role : user.getRoles()) {
// if (!StringUtils.isBlank(role.getName())) {
// log.debug("授予角色>>>" + role.getName());
// roleList.add(role.getName());
// }
// }
// }
// // 实体类User中包含有角色权限的实体类信息
// if (null != user.getPermissions() && user.getPermissions().size() > 0) {
// for (Permission pmss : user.getPermissions()) {
// if (!StringUtils.isBlank(pmss.getPermission())) {
// log.debug("授予权限>>>>" + pmss.getPermission());
// permissionList.add(pmss.getPermission());
// }
// }
// }
// } else {
// throw new AuthorizationException();
// }
// 为当前用户设置角色和权限
SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
simpleAuthorInfo.addRoles(roleList);
simpleAuthorInfo.addStringPermissions(permissionList); return simpleAuthorInfo;
} /**
* 验证当前登录的Subject
* 认证回调函数,登录时调用.
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
throws AuthenticationException {
// 获取基于用户名和密码的令牌
UsernamePasswordToken token = (UsernamePasswordToken) authcToken; SysUsers user = userService.getUserByUsername(token.getUsername()); AuthenticationInfo authcInfo = null;
if (user == null) {
throw new UnknownAccountException();// 未知账户
}
else if(!user.getPassword().equals(ParseMD5.parseStrToMd5L32(String.valueOf(token.getPassword())))){
throw new UnknownAccountException();// 账户密码错误,与管理员联系
}
else if (user.getStatus() == 0) {
throw new LockedAccountException();// 账户已锁定,与管理员联系
}
else {
authcInfo = new SimpleAuthenticationInfo(user.getUsername(),
token.getPassword(),
getName()); this.setSession("currentUser", user.getUsername());
} return authcInfo;
} /**
* 更新授权信息缓存
*/
public void clearCachedAuthorizationInfo(String principal) {
SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
clearCachedAuthorizationInfo(principals);
} /**
* ShiroSession设置
*
* @see 使用时直接用HttpSession.getAttribute(key)就可以取到
*/
private void setSession(Object key, Object value) {
Subject currentUser = SecurityUtils.getSubject();
if (null != currentUser) {
Session session = currentUser.getSession();
if (null != session) {
session.setAttribute(key, value);
}
}
}
}
在spring的配置文件中配置:新建spring-shrio.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"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
- <!-- 配置权限管理器 -->
- <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
- <!-- ref对应我们写的realm MyShiro -->
- <property name="realm" ref="myShiro"/>
- <!-- 使用下面配置的缓存管理器 -->
- <property name="cacheManager" ref="cacheManager"/>
- </bean>
- <!-- 配置shiro的过滤器工厂类,id- shiroFilter要和我们在web.xml中配置的过滤器一致 -->
- <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
- <!-- 调用我们配置的权限管理器 -->
- <property name="securityManager" ref="securityManager"/>
- <!-- 配置我们的登录请求地址 -->
- <property name="loginUrl" value="/login"/> <!--login方法我们自定义一个控制器-->
- <!-- 配置我们在登录页登录成功后的跳转地址,如果你访问的是非/login地址,则跳到您访问的地址 -->
- <property name="successUrl" value="/main"/>
- <!-- 如果您请求的资源不再您的权限范围,则跳转到/unauthorized请求地址 -->
- <property name="unauthorizedUrl" value="/unauthorized"/>
- <!-- 权限配置 -->
- <property name="filterChainDefinitions">
- <value>
- <!-- anon表示此地址不需要任何权限即可访问 -->
- /static/**=anon
- <!-- perms[user:query]表示访问此连接需要权限为user:query的用户 -->
- /user=perms[user:query]
- <!-- roles[manager]表示访问此连接需要用户的角色为manager -->
- /user/add=roles[manager]
- /user/del/**=roles[admin]
- /user/edit/**=roles[manager]
- <!--所有的请求(除去配置的静态资源请求或请求地址为anon的请求)都要通过登录验证,如果未登录则跳到/login-->
- /** = authc
- </value>
- </property>
- </bean>
- <bean id="myShiro" class="ShrioRealm"/><!--权限控制类的全类名-->
- <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />
- <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
- </beans>
对于登录,未授权,错误的请求url写上请求控制处理方法:
package net.lcheng.manage.controller; import net.lcheng.commons.utils.ParseMD5;
import net.lcheng.manage.utils.ControllerUtils;
import net.lcheng.manage.vo.PasswordModel;
import net.lcheng.model.SysUsers;
import net.lcheng.service.SysPermissionsService;
import net.lcheng.service.SysUsersService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import javax.validation.Valid; @Controller
public class HomeController { @Autowired
private SysUsersService usersService;
@Autowired
private SysPermissionsService permissionsService; @RequestMapping("/main")
// @RequiresRoles("admin")
// @RequiresPermissions("user:create")
public String main(Model model) throws Exception {
ControllerUtils.common(model,permissionsService,"");
return "main";
} /**权限不足错误页面*/
@RequestMapping("/unauthorized")
public String unauthorized(Model model){
Subject currentUser = SecurityUtils.getSubject();//获取当前用户
if(currentUser.isAuthenticated()) {
model.addAttribute("userName",currentUser.getPrincipals());
}
return "unauthorized";
} /**错误页面*/
@RequestMapping("/error")
public String error(Model model){
Subject currentUser = SecurityUtils.getSubject();//获取当前用户
if(currentUser.isAuthenticated()) {
model.addAttribute("userName",currentUser.getPrincipals());
}
return "error";
} @RequestMapping(value = "/change_pwd",method = RequestMethod.GET)
public String changePwd(Model model){
model.addAttribute("PasswordModel",new PasswordModel());
ControllerUtils.common(model,permissionsService,""); return "change_pwd";
}
@RequestMapping(value = "/change_pwd",method = RequestMethod.POST)
public String changePwdPost(Model model,@Valid @ModelAttribute("PasswordModel") PasswordModel user, BindingResult result){
Subject currentUser = SecurityUtils.getSubject();//获取当前用户
ControllerUtils.common(model,permissionsService,""); if (result.hasErrors()) {
return "change_pwd";
} SysUsers sysUser = usersService.getUserByUsername(currentUser.getPrincipals().toString());
if(sysUser!=null) {
if(!sysUser.getPassword().equals(ParseMD5.parseStrToMd5L32(user.getOldPwd()))){
model.addAttribute("error", "原密码错误");
return "change_pwd";
}
if(!user.getNewPwd().equals(user.getRePwd())){
model.addAttribute("error", "二次密码不一致");
return "change_pwd";
} if(ParseMD5.parseStrToMd5L32(user.getNewPwd()).equals(ParseMD5.parseStrToMd5L32(user.getOldPwd()))){
model.addAttribute("error", "新密码和原密码一样");
return "change_pwd";
} usersService.changePassword(sysUser.getId(), ParseMD5.parseStrToMd5L32(user.getNewPwd()));
model.addAttribute("error", "密码修改成功,请使用新密码重新登录!");
}else{
model.addAttribute("error", "用户不存在");
} return "change_pwd";
} }
package net.lcheng.manage.controller; import net.lcheng.commons.utils.ParseMD5;
import net.lcheng.manage.vo.LoginEntity;
import net.lcheng.model.SysUsers;
import net.lcheng.service.SysUsersService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import javax.validation.Valid; /**
* Created by qiliping on 15/12/1.
* 登录Controller
*/
@Controller
public class LoginController {
@Autowired
private SysUsersService sysUsersService; /**
* 登录GET
*/
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String Index(Model model) {
if (!model.containsAttribute("LoginEntity")) {
model.addAttribute("LoginEntity", new LoginEntity());
}
return "login";
} /***
* 用户登陆
* <p>注解配置,只允许POST提交到该方法
*
* @param username
* @param password
* @return
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(Model model, @Valid @ModelAttribute("LoginEntity") LoginEntity user, BindingResult result) {
if (result.hasErrors()) {
return "login";
}
SysUsers userModel = sysUsersService.getUserByUsername(user.getUsername()); if (userModel != null) {
String inputPwd = ParseMD5.parseStrToMd5L32(user.getPassword());
if (!userModel.getPassword().equals(inputPwd)) {
model.addAttribute("error", "登录密码错误");
return "login";
}
if (userModel.getStatus() != 1) {
model.addAttribute("error", "无效的用户");
return "login";
}
//登录成功
SecurityUtils.getSubject().login(new UsernamePasswordToken(user.getUsername(), user.getPassword()));
return "redirect:/main";
} else {
model.addAttribute("error", "用户不存在");
return "login";
} } /***
* 退出
* @param model
* @return
*/
@RequestMapping(value = "logout")
public String logout(Model model) { SecurityUtils.getSubject().logout(); return "redirect:/login"; } /***
* 验证参数是否为空
*
* @param params
* @return
*/
private boolean checkParams(String[] params) {
for (String param : params) {
if (param == "" || param == null || param.isEmpty()) {
return false;
}
}
return true;
}
}
SpringMVC集成shrio框架的更多相关文章
- SpringMVC集成缓存框架Ehcache
在互联网应用中,应用并发比传统企业及应用会高出很多.解决并发的根本在于系统的响应时间与单位时间的吞吐量.思路可分为:一减少系统的不必要开支(如缓存),二是提高系统单位时间内的运算效率(如集群). 在硬 ...
- SpringMVC整合Tiles框架
SpringMVC整合Tiles框架 Tiles组件 tiles-iconfig.xml Tiles是一个JSP布局框架. Tiles框架为创建Web页面提供了一种模板机制,它能将网页的布局和内容分离 ...
- SpringMVC集成springfox-swagger2自动生成接口文档
本节内容: 什么是Swaggger Springfox与Swagger的关系 SpringMVC集成springfox-swagger2 一.什么是Swaggger Swagger是一个流行的API开 ...
- MP实战系列(十)之SpringMVC集成SpringFox+Swagger2
该示例基于之前的实战系列,如果公司框架是使用JDK7以上及其Spring+MyBatis+SpringMVC/Spring+MyBatis Plus+SpringMVC可直接参考该实例. 不过建议最好 ...
- Spring学习之旅(六)--SpringMVC集成
对大多数 Java 开发来说,基于 web 的应用程序是我们主要的关注点. Spring 也提供了对于 web 的支持,基于 MVC 模式的 Spring MVC 能够帮助我们灵活和松耦合的完成 we ...
- Spring Boot集成Shrio实现权限管理
Spring Boot集成Shrio实现权限管理 项目地址:https://gitee.com/dsxiecn/spring-boot-shiro.git Apache Shiro是一个强大且 ...
- 手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)
手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版) SSM(Spring+SpringMVC+Mybatis),目前较为主流的企业级架构方案.标准的MVC设计模式, ...
- EhCache WebCache 与 SpringMVC集成时 CacheManager冲突的问题
转自:点击打开链接 http://www.cnblogs.com/daxin/p/3560989.html EhCache WebCache 与 SpringMVC集成时 CacheManager冲突 ...
- Springmvc整合tiles框架简单入门示例(maven)
Springmvc整合tiles框架简单入门示例(maven) 本教程基于Springmvc,spring mvc和maven怎么弄就不具体说了,这边就只简单说tiles框架的整合. 先贴上源码(免积 ...
随机推荐
- centos6.5 安装zabbix
实验说明: 操作系统: CentOS6.5 64位 Web环境: Apache Mysql PHP zabbix版本: LTS 2.2.10 Linux服务器IP: 10.0.0.2 Linux客户端 ...
- [UWP小白日记-2]SQLite数据库DOME
数据库说简单点就是增删改查,但是对新手来说也是要爆肝的.作为一个新手爆肝无数次啊, 血的教训啊现在UWP的教程又少,说多了都是泪.留下来免得以后又爆肝.还有:一定要写注释!一定要写注释!一定要写注释! ...
- Spring Security(19)——对Acl的支持
目录 1.1 准备工作 1.2 表功能介绍 1.2.1 表acl_sid 1.2.2 表acl_class 1.2.3 表acl_obj ...
- sql注入示例
实验指导说明 实验环境 • 实验环境 o 操作机:Windows XP o 目标机:Windows 2003 o 目标网址:www.test.ichunqiu • 实验工具: Tools Path S ...
- 使用高通SDK开发AR应用
具体AR是什么效果我这里就不说了,直接上过程: 1.去官网注册一个帐号https://developer.vuforia.com 2.下载SDK for Unity,并导入Unity 3.点击Deve ...
- 【转载】__name__ == "__main__": 你认识我么?
<笨方法学Python>的习题50中,脚本ex50.py最后一行代码就是 if __name__ == "__main__": 那么,这句代码到底有什么用呢? 莫急莫急 ...
- oc 导航栏跳转指定界面
[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIn ...
- 服务管理--systemctl命令
摘要: systemctl 是系统服务管理器命令,它实际上将 service 和 chkconfig 这两个命令组合到一起. 任务 旧指令 新指令 使某服务自动启动 chkconfig --level ...
- My97DatePicker -- 一个功能丰富, 而且兼容 ie 6, 7的日期选择组件
easyUI 也提供了 功能强大的日期组件, 可惜在ie 6,7,8下会报错,没有找到 addEventListener , JSON, 可能现在不想再支持低版本ie了 另外avalon也提供了 日 ...
- wxWidgets显示视频
wxWidgets中似乎没有专门用于显示视频的控件(虽然有wxWidgets本身的openGL控件wxGLCANVAS,但是我没有去试--) 按照这篇文章所讲的,从wxPanel继承出一个DrawPa ...