一、需要是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";
@Autowired
private UserService userServiceImpl;
@Override
protected 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;
}
@Override
protected 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());
@Autowired
private 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>
共同探讨,一起进步!