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>