spring中集成shiro进行安全管理
shiro是一款轻量级的安全框架,提供认证、授权、加密和会话管理四个基础功能,除此之外也提供了很好的系统集成方案。
下面将它集成到之前的demo中,在之前spring中使用aop配置事务这篇所附代码的基础上进行集成
一、添加jar包引用
修改pom.xml文件,加入:
<!-- security -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-cas</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.2.5</version>
</dependency>
二、添加过滤器Filter
修改web.xml文件,加入(需要加在Filter比较靠前的位置):
<!-- Shiro过滤器 -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
三、添加配置文件
在"src/main/resources"代码文件夹中新建文件"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"
xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <description>Shiro Configuration</description> <!-- 加载配置属性文件 -->
<context:property-placeholder ignore-unresolvable="true" location="classpath:demo.properties" /> <!-- 定义安全管理配置 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm" />
<property name="sessionManager" ref="defaultWebSessionManager" />
<!-- <property name="cacheManager" ref="shiroCacheManager" /> -->
</bean>
<bean id="userRealm" class="org.xs.demo1.UserRealm"></bean> <!-- 自定义会话管理 -->
<bean id="defaultWebSessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<!-- 会话超时时间,单位:毫秒 -->
<property name="globalSessionTimeout" value="86400000" />
<!-- 定时清理失效会话, 清理用户直接关闭浏览器造成的孤立会话 -->
<property name="sessionValidationInterval" value="120000"/>
<!-- 定时检查失效的会话 -->
<property name="sessionValidationSchedulerEnabled" value="true"/>
</bean> <!-- 安全认证过滤器 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<property name="loginUrl" value="/hello/login" />
<property name="unauthorizedUrl" value="/hello/login" />
<property name="successUrl" value="/hello/mysql" />
<property name="filterChainDefinitions">
<value>
/hello/login = anon //anon:允许匿名访问
/hello/auth = anon
/hello/* = authc //authc:需要认证才能访问
</value>
</property>
</bean> <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
</beans>
四、增加安全认证实现类
在"src/main/java"代码文件夹的"org.xs.demo1"的包下新建"UserRealm.java"
package org.xs.demo1; import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Service; /**
* 安全认证实现类
*/
@Service
public class UserRealm extends AuthorizingRealm { /**
* 获取授权信息
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { //String currentUsername = (String) getAvailablePrincipal(principals); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addStringPermission("admin"); return info;
} /**
* 获取认证信息
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; String username = token.getUsername();
if (username != null && !"".equals(username)) {
return new SimpleAuthenticationInfo("xs", "123", getName());
}
return null;
}
}
五、增加Controller方法
在HelloController类里添加方法:
/**
* 登录页
*/
@RequestMapping("login")
public String login() throws Exception {
return "login";
} /**
* 登录验证
*/
@RequestMapping("auth")
public String auth(String loginName, String loginPwd) throws Exception { SecurityUtils.getSecurityManager().logout(SecurityUtils.getSubject()); if(!"xs".equals(loginName) || !"123".equals(loginPwd)) {
return "redirect:/hello/login";
} UsernamePasswordToken token = new UsernamePasswordToken(loginName, loginPwd);
Subject subject = SecurityUtils.getSubject();
subject.login(token); return "redirect:/hello/mysql";
}
六、增加login.jsp页面
在WEB-INF的views文件夹中新建"login.jsp"
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<%
/* 当前基础url地址 */
String path = request.getContextPath();
request.setAttribute("path", path);
%>
</head>
<body>
<form action="${path}/hello/auth" method="post">
登录名称:<input type="text" name="loginName" value="${userInfo.loginName}" />
登录密码:<input type="text" name="loginPwd" value="${userInfo.loginPwd}" />
<input type="submit" class="btn btn-default btn-xs" value="保存" />
</form>
</body>
</html>
七、运行测试
访问"http://localhost:8080/demo1/hello/mysql"的地址,页面会被跳转到登陆页:

输入用户名"xs"和密码"123",然后点击登录,就能跳转到mysql:

实例代码地址:https://github.com/ctxsdhy/cnblogs-example
spring中集成shiro进行安全管理的更多相关文章
- spring中集成shiro
Shiro的组件都是JavaBean/POJO式的组件,所以非常容易使用Spring进行组件管理,可以非常方便的从ini配置迁移到Spring进行管理,且支持JavaSE应用及Web应用的集成. 在示 ...
- 细说shiro之五:在spring框架中集成shiro
官网:https://shiro.apache.org/ 1. 下载在Maven项目中的依赖配置如下: <!-- shiro配置 --> <dependency> <gr ...
- [原]CAS和Shiro在spring中集成
shiro是权限管理框架,现在已经会利用它如何控制权限.为了能够为多个系统提供统一认证入口,又研究了单点登录框架cas.因为二者都会涉及到对session的管理,所以需要进行集成. Shiro在1.2 ...
- 十一、Spring Boot 集成Shiro和CAS
1.Shiro 是什么?怎么用? 2.Cas 是什么?怎么用? 3.最好有spring基础 首先看一下下面这张图: 第一个流程是单纯使用Shiro的流程. 第二个流程是单纯使用Cas的流程. 第三个图 ...
- Spring Boot 集成Shiro和CAS
Spring Boot 集成Shiro和CAS 标签: springshirocas 2016-01-17 23:03 35765人阅读 评论(22) 收藏 举报 分类: Spring(42) 版 ...
- 解决Spring Boot集成Shiro,配置类使用Autowired无法注入Bean问题
如题,最近使用spring boot集成shiro,在shiroFilter要使用数据库动态给URL赋权限的时候,发现 @Autowired 注入的bean都是null,无法注入mapper.搜了半天 ...
- Spring Boot集成Shiro实战
Spring Boot集成Shiro权限验证框架,可参考: https://shiro.apache.org/spring-boot.html 引入依赖 <dependency> < ...
- 在前后端分离的SpringBoot项目中集成Shiro权限框架
参考[1].在前后端分离的SpringBoot项目中集成Shiro权限框架 参考[2]. Springboot + Vue + shiro 实现前后端分离.权限控制 以及跨域的问题也有涉及
- Spring Boot 中集成 Shiro
https://blog.csdn.net/taojin12/article/details/88343990
随机推荐
- 性能测试学习第二天-----loadrunner常用函数大全及设置项
常用函数大全: 1,C语言参数转web参数 lr_save_string("aaa","param"):将字符串“aaa”或者一个字符串变量,转变成LR的参数{ ...
- LoRaWAN调试踩坑心得(二)
先说两句 抱歉,由于工作原因和个人原因,中间停更了这么久.接下来,本人会继续往下更,内容包括但不仅限于LoRa.文章还是会按照个人的习惯,坚持原创,一是作为自己的笔记,二是和广大工程师分享交流. Lo ...
- springboot启动慢解决方法
jdk的配置文件中,使用securerandom.source设置了熵源: cat /usr/java/jdk1.8.0_121/jre/lib/security/java.security secu ...
- springCould:使用Feign 实现声明式服务调用
一.Spring Cloud Feign概念引入通过前面的随笔,我们了解如何通过Spring Cloud ribbon进行负责均衡,如何通过Spring Cloud Hystrix进行服务断路保护,两 ...
- 服务器小白的我,是如何将 node+mongodb 项目部署在服务器上并进行性能优化的
前言 本文讲解的是:做为前端开发人员,对服务器的了解还是小白的我,是如何一步步将 node+mongodb 项目部署在阿里云 centos 7.3 的服务器上,并进行性能优化,达到页面 1 秒内看到 ...
- 缓存系列-Redis入门教程
Redis是什么? Redis (REmote DIctionary Server)是一个开源(BSD许可),内存存储的数据结构服务器,可用作数据库,高速缓存和消息队列,是一个高性能的key-valu ...
- .Net Core 2.2与Java 12性能对比
我发现基准游戏(https://benchmarksgame-team.pages.debian.net/benchmarksgame/fastest/csharp.html)是一套非常好的基准测试. ...
- SDU暑期集训排位(9)
SDU暑期集训排位(9) G. Just Some Permutations 基础 DP 练习部分 定义 \(f(S)\),表示让 S 中的人全 happy 的方案数. \(dp[i][j]\) 表示 ...
- 【转 | 侵删】2D 绘图技术中的坐标系统与坐标变换
本文介绍在 2D 绘图技术中的坐标系统和坐标变换的相关知识.同时介绍 Kity 在这方面提供的 API .希望这些知识对于需要进行图形应用开发的同学会有所帮助. 锤子的故事 很久以前,有一个画家,他很 ...
- 牛客网暑期ACM多校训练营(第三场) C Shuffle Cards 平衡树 rope的运用
链接:https://www.nowcoder.com/acm/contest/141/C来源:牛客网 Eddy likes to play cards game since there are al ...