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

最新文章

  1. 最新Angular2案例rebirth开源
  2. JQuery 滚动轮播
  3. Adobe AIR 中为不同尺寸和分辨率屏幕适配
  4. beanstalkd----协议
  5. Solr auto commit 配置
  6. JVM-运行时数据区
  7. winform 打包部署
  8. C++ 使用cl命令编辑时发生的问题收录
  9. 2018/2/13 ElasticSearch学习笔记三 自动映射以及创建自动映射模版,ElasticSearch聚合查询
  10. Android热修复原理
  11. Busybox制作ARM(iTOP4412) 根文件系统
  12. Java连接SqlServer 2008数据库
  13. Python api认证
  14. Factorial Trailing Zeroes (Divide-and-Conquer)
  15. ubuntu 创建容器 并ssh 连接容器
  16. openwrt编译系统生成ubi镜像的各变量解析
  17. Django--缓存、信号、序列化
  18. 重新看《JavaScript高级程序设计》
  19. 创建 cordova 项目
  20. 前端webview开发中遇到的一些问题及其解决方法

热门文章

  1. POJ 3186
  2. PHP 与 MySQL 相关操作
  3. Spring框架入门之基于Java注解配置bean
  4. session一致性的解决方案
  5. .NET Core 学习资料精选:进阶
  6. SpringBoot 2 快速整合 | 统一异常处理
  7. Oracle批量更改所有表的字段取值_类型_原字段名
  8. mysql登录的root密码问题
  9. Python中yield解析
  10. xcode7中搭建python开发环境