1、配置文件
application-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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 声明凭证配置器,在db中存的是md5加密字符串 -->
<bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!-- 加密凭证 -->
<property name="hashAlgorithmName" value="md5"></property>
<!-- 加密次数 -->
<property name="hashIterations" value="2"></property>
</bean>
<!-- 注入userRealm -->
<bean id="userRealm" class="com.wcong.realm.UserRealm">
<property name="credentialsMatcher" ref="credentialsMatcher"></property>
</bean>
<!-- 配置securityManager,注意和java中使用的类不一样 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm"></property>
</bean>
<!-- 配置shiro的过滤规则。注意这里的id必须和web.xml里面的配置一样 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- 注入安全管理器 -->
<property name="securityManager" ref="securityManager"></property>
<!-- 配置未登录跳转的页面,默认是webapp/login.jsp -->
<property name="loginUrl" value="/index.jsp"></property>
<!-- 配置未授权的访问页面 -->
<property name="unauthorizedUrl" value="/unauthorized.jsp"></property>
<property name="filterChainDefinitionMap">
<map>
<!-- 放行login.jsp -->
<entry>
<key><value>/login.jsp*</value></key>
<value>anon</value>
</entry>
<!-- 放行跳转到登录页面的路径 -->
<entry>
<key><value>/login/toLogin**</value></key>
<value>anon</value>
</entry>
<!-- 放行登录请求 -->
<entry>
<key><value>/login/login*</value></key>
<value>anon</value>
</entry>
<!-- 设置退出登录的路径 -->
<entry>
<key><value>/login/logout*</value></key>
<value>anon</value>
</entry>
<!-- 设置其他路径全部拦截 -->
<entry>
<key><value>/**</value></key>
<value>authc</value>
</entry>
</map>
</property>
</bean>
</beans>
web.xml
在 web-app 节点下面配置
<!-- 配置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>
<init-param>
<!-- 这里的shrioFilter必须和application-shrio.xml里面的 过滤器ID一致 -->
<param-name>targetBeanName</param-name>
<param-value>shiroFilter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<servlet-name>springmvc</servlet-name>
</filter-mapping>
<!-- 配置shiro的代理过滤器 结束 -->
java代码
UserRealm .java
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Autowired
private PermissionService permissionService;
@Override
public String getName() {
// TODO Auto-generated method stub
return this.getClass().getSimpleName();
}
/**
* 登录
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// 获取username
String username = token.getPrincipal().toString();
// 通过username获取User
User user = userService.queryUserByUserNmae(username);
if(null != user) {
// 得到所有角色
List<String> roles = roleService.queryRolesByUserId(user.getUserid());
List<String> permissions = permissionService.queryPermissionByUserId(user.getUserid());
// 构建ActiveUser
ActiveUser activeUser = new ActiveUser();
activeUser.setRoles(roles);
activeUser.setPermissions(permissions);
activeUser.setUser(user);
ByteSource credentialsSalt = ByteSource.Util.bytes(user.getUsername()+user.getAddress());
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(activeUser, user.getUserpwd(), credentialsSalt, this.getName());
return info;
}else {
return null;
}
}
/**
* 授权
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// 取出activeUser
ActiveUser active = (ActiveUser) principals.getPrimaryPrincipal();
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
List<String> roles = active.getRoles();
List<String> permissions = active.getPermissions();
// 添加角色和权限
if(null != roles && roles.size() > 0) {
info.addRoles(roles);
}
if(null != permissions && permissions.size()> 0) {
info.addStringPermissions(permissions);
}
return info;
}
}
Controller
/**
* 登录
* @param username
* @param pwd
* @param sesion
* @return
*/
@RequestMapping("/login")
public String login(String username,String pwd,HttpSession sesion) {
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username,pwd);
try {
// 登录成功
subject.login(token);
ActiveUser active = (ActiveUser) subject.getPrincipal();
sesion.setAttribute("user", active.getUser());
// 跳转到用户管理界面
return "redirect:/user/toUserManager.action";
} catch (Exception e) {
// 登录失败
e.printStackTrace();
// 登录界面,重定向不走视图解析器
return "redirect:/index.jsp";
}
}
用户管理界面的JSP界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 判断用户的某一权限是否存在 -->
<shiro:hasPermission name="person:add">
<h2>添加用户</h2>
</shiro:hasPermission>
<shiro:hasPermission name="person:query">
<h2>查询用户</h2>
</shiro:hasPermission>
<shiro:hasPermission name="person:update">
<h2>修改用户</h2>
</shiro:hasPermission>
<shiro:hasPermission name="person:delete">
<h2>删除用户</h2>
</shiro:hasPermission>
<shiro:hasPermission name="person:export">
<h2>导出用户</h2>
</shiro:hasPermission>
</body>
</html>