spring+apache shiro demo
来源:互联网 发布:兴奋剂 知乎 编辑:程序博客网 时间:2024/05/22 08:11
一、需要是shiro依赖
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>${shiro.vesion}</version></dependency><dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>${shiro.vesion}</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-ehcache</artifactId><version>1.2.1</version></dependency>
二、在wen.xml加入过滤器
<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>
三、spring配置文件
<?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-3.1.xsd"default-lazy-init="true"><description>Shiro安全配置</description><bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"><property name="securityManager" ref="securityManager"/><property name="loginUrl" value="/login.action"></property><property name="successUrl" value="/index.jsp"></property><!-- 登录成功跳转到index.jsp 默认的很奇怪 --><property name="unauthorizedUrl" value="/error.jsp"></property><!-- 没有认证成功,或者没有权限,跳转到错误页面 --><property name="filterChainDefinitions"><value> /init.action = authc /login.action = authc /test.action = authc /reportDetail.action = authc,perms["access"] <!-- 权限 --> /testRole.action = authc,roles["admin"] <!-- 角色--> /logout.action = logout /** = authc</value></property></bean><bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"><property name="realm" ref="realm"/><property name="cacheManager" ref="ehCacheShiro"></property> </bean><bean id="realm" class="com.csair.shiro.MyShiroRealm"></bean><bean id="ehCacheShiro" class="org.apache.shiro.cache.ehcache.EhCacheManager"><property name="cacheManagerConfigFile" value="classpath:cache/ehcache-shiro.xml"/></bean> <!-- 保证实现了Shiro内部lifecycle函数的bean执行 --><bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/></beans>
四、重写AuthorizingRealm中的模板方法
package com.csair.shiro;import org.apache.log4j.Logger;import org.apache.shiro.SecurityUtils;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.apache.shiro.subject.Subject;import org.springframework.beans.factory.annotation.Autowired;import com.csair.entity.UserAnotation;import com.csair.service.UserService;public class MyShiroRealm extends AuthorizingRealm {private Logger log = Logger.getLogger(this.getClass());private static final String MESSAGE = "message";@Autowiredprivate UserService userServiceImpl;@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {System.out.println("授权");String username = (String)principals.getPrimaryPrincipal();SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();if("ppt".equals(username)) {info.addStringPermission("access");return info;}if("jpa".equals(username)) {info.addStringPermission("access");info.addRole("admin");return info;}return null;}@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {System.out.println("认证"); UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; String username = token.getUsername(); String passwrod = null; if(token.getPassword() != null) { passwrod = new String(token.getPassword()); } if(username == null || "".equals(username)) { this.setAttribute(MESSAGE, "用户名不能为空"); log.info("用户名为空"); return null; } if(passwrod == null || "".equals(passwrod)) { this.setAttribute(MESSAGE, "密码不能为空"); log.info("密码为空"); return null; } UserAnotation user = null; if(token.getUsername() != null && !"".equals(token.getUsername())) { user = userServiceImpl.getUserByName(token.getUsername()); } try { return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),getName()); } catch(Exception e) { log.info("用户名或密码错误"); setAttribute(MESSAGE, "用户名或密码错误"); return null; } }private void setAttribute(String key, String value) {SecurityUtils.getSubject().getSession().setAttribute(key, value);}}
五、action测试
package com.csair.action;import org.apache.log4j.Logger;import org.apache.struts2.convention.annotation.Action;import org.apache.struts2.convention.annotation.Result;import org.springframework.beans.factory.annotation.Autowired;import com.csair.dao.SpringDataJpa;import com.csair.entity.UserAnotation;public class strutsDemoAction {private String username;private String password;private Logger log = Logger.getLogger(this.getClass());@Autowiredprivate SpringDataJpa springDataJpa;@Action(value="login")public String login() {log.info("初始化");return "login";}@Action(value="test", results={@Result(name="test", location="report.jsp")})public String testStrutsAnotation() {log.info("登录成功");UserAnotation user = springDataJpa.findOne(9, UserAnotation.class);System.out.println(user.toString());return "test";}@Action(value="reportDetail", results=@Result(name="reportDetail", location="reportDetail.jsp"))public String reportDetail() {try {log.info("报表登录");UserAnotation aa = new UserAnotation();aa.setUsername("ppt");aa.setPassword("ppt");} catch(Exception e) {e.printStackTrace();}return "reportDetail";}@Action(value="logout", results=@Result(name="logout", location="login.jsp"))public String logout() {log.info("退出登录");return "logout";}@Action(value="testRole", results=@Result(name="testRole", location="sendSms.jsp"))public String testRole() {log.info("testRole");return "testRole";}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}
六、缓存配置文件
<ehcache updateCheck="false" name="shiroCache"> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" /></ehcache>
共同探讨,一起进步!
- spring+apache shiro demo
- Apache shiro(2)—first Demo(web+spring+shiro)
- Apache Shiro 集成-spring
- spring+apache shiro登录
- Apache Shiro 集成-spring
- apache shiro+spring简单集成
- apache shiro整合spring(一)
- spring springmvc shiro 实现单点登录demo
- Shiro+Spring整合(超详细,有demo)
- spring+springmvc+mybatis+shiro+ehcache集成demo
- Apache shiro学习笔记+ spring整合shiro (一)
- [翻译-Shiro]-集成Apache Shiro到基于Spring的应用
- apache shiro与spring的环境搭建
- Spring集成Apache Shiro安全框架
- Apache Shiro with Spring学习笔记
- Apache Shiro与Spring Security学习
- Apache shiro 笔记整理之整合spring
- Apache Shiro 与 Spring框架整合
- ITU-T-REC-G.1080-IPTV的体验质量(QoE)要求(三)
- HTML5 新增标签兼容处理
- 关于Invalidate、InvalidateRect和UpdateWindow
- 计算选手最后得分(限制分的值,且最后按n或N键结束,其他键继续)
- java基础--Jar包添加到build path方式说明--01
- spring+apache shiro demo
- MyEclipse6.0编译后的类无法自动发不到WebRoot/WEB-INF/classes文件夹下(转)
- Scrum敏捷开发&管理--计划启动
- 一个懦弱的IT人
- VC 如何使程序运行后自己删除自己
- mina线程总结
- Linux文件系统
- 你看透了这些,别人就看不透你
- 电脑培训知识-网站第一屏(幕)应该如何设计