原文連接:http://blog.csdn.net/qq_37936542/article/details/79010449css
springmvc+shiro實現系統粗細粒度的權限管理步驟:html
1:表格設計前端
2:配置maven依賴java
3:web.xml配置shiro過濾器mysql
4:web.xml引入applicationContext-shiro.xml的配置文件web
5:配置applicationContext-shiro.xml配置文件spring
6:配置shiro緩存文件sql
7:自定義realm實現用戶認證和受權express
8:實現登陸邏輯apache
9:頁面控制權限
一:表格設計(一個用戶對應一個系統角色,一個系統角色具備多個操做權限)
二:導入相關依賴 pom.xml
三:web.xml配置shiro攔截器
- <!-- 這裏的filter-name 要和spring 的applicationContext-shiro.xml 裏的
- g.apache.shiro.spring.web.ShiroFilterFactoryBean 的bean name 相同 -->
- <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>
四:web.xml引入applicationContext-shiro.xml文件
-
- <servlet>
- <servlet-name>dispatcherServlet</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
-
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:spring/springmvc-servlet.xml,classpath:spring/applicationContext*.xml</param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>dispatcherServlet</servlet-name>
- <url-pattern>/</url-pattern>
- </servlet-mapping>
配置文件目錄結構:
五:配置applicationContext-shiro.xml文件
-
- <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
- <property name="realm" ref="shiroDbRealm"/>
-
- <property name="cacheManager" ref="cacheManager"/>
- </bean>
-
-
- <bean id="shiroDbRealm" class="com.debo.login.controller.ShiroDbRealm"/>
-
-
- <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
- <property name="securityManager" ref="securityManager"/>
- <property name="loginUrl" value="/login.jsp" />
- <property name="unauthorizedUrl" value="/noPromission.jsp" />
- <property name="filterChainDefinitions">
- <value>
- /css/** = anon
- /img/** = anon
- /js/** = anon
- /jsp/** = user
- /web/** = anon
- /**/**=user
- </value>
- </property>
- </bean>
-
-
- <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
- <property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/>
- </bean>
-
-
- <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
六:配置ehcache-shiro.xml文件
- <ehcache updateCheck="false" name="shiroCache">
-
- <defaultCache
- maxElementsInMemory="10000"
- eternal="false"
- timeToIdleSeconds="120"
- timeToLiveSeconds="120"
- overflowToDisk="false"
- diskPersistent="false"
- diskExpiryThreadIntervalSeconds="120"
- />
- </ehcache>
七:自定義realm AuthRealm
- package com.debo.login.controller;
-
- import java.util.List;
-
- 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.beans.factory.annotation.Autowired;
-
- import com.debo.security.pojo.User;
- import com.debo.security.service.RoleService;
- import com.debo.security.service.UserService;
-
- public class ShiroDbRealm extends AuthorizingRealm {
-
- @Autowired
- private UserService userService;
- @Autowired
- private RoleService roleService;
-
- /**
- * shiro認證
- */
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(
- AuthenticationToken authcToken) throws AuthenticationException {
-
- UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
- String loginName = token.getUsername();
- if (loginName != null && !"".equals(loginName)) {
- // 通過登陸名獲取用戶
- User user = userService.getUserByLoginName(loginName);
- if (user != null) {
- // 若是身份認證驗證成功,返回一個AuthenticationInfo實現
- return new SimpleAuthenticationInfo(user.getLoginName(),
- user.getPassword(), getName());
- }
- }
- return null;
- }
-
- /**
- * shiro受權
- */
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(
- PrincipalCollection principals) {
- String loginName = (String) getAvailablePrincipal(principals); // 使用Shiro提供的方法獲取用戶名稱
- if (loginName != null) {
- String roleId = userService.getRoleIdByLoginName(loginName);
-
- // 獲取用戶的權限
- List<String> permTokens = roleService.getPermTokens(roleId);
-
- SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
- if (roleId != null) {
- info.addRole(roleId); // 加入用戶角色
- }
- if (permTokens != null) {
- info.addStringPermissions(permTokens); // 加入用戶許可標記
- }
- return info;
- }
- return null;
- }
- }
八:書寫登陸邏輯
- package com.debo.login.controller;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpSession;
-
- import org.apache.shiro.SecurityUtils;
- import org.apache.shiro.authc.AuthenticationException;
- import org.apache.shiro.authc.UsernamePasswordToken;
- import org.apache.shiro.subject.Subject;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.context.ContextLoader;
- import org.springframework.web.context.WebApplicationContext;
- import org.springframework.web.servlet.mvc.support.RedirectAttributes;
-
- import com.debo.company.service.CompanyService;
- import com.debo.develop.service.MenuService;
- import com.debo.security.pojo.User;
- import com.debo.security.service.UserService;
-
-
- @Controller
- @RequestMapping("/login")
- public class LoginController {
-
- @Autowired
- private MenuService menuService;
-
- @Autowired
- private UserService userService;
-
- @Autowired
- private CompanyService companyService;
-
- @RequestMapping(method = {RequestMethod.GET})
- public String login(HttpServletRequest request) {
- System.out.println("歡迎登錄!……");
- return "/login";
- }
-
- @RequestMapping(method = {RequestMethod.POST})
- public String loginPost(User user, RedirectAttributes redirectAttributes, HttpServletRequest request) {
- Subject currentUser = SecurityUtils.getSubject();
- UsernamePasswordToken token = new UsernamePasswordToken(user.getLoginName(), user.getPassword(), user.isRememberMe());
- try {
- //用戶認證
- currentUser.login(token);
- } catch (AuthenticationException e) {
- System.out.println(e);
- redirectAttributes.addFlashAttribute("message", "用戶名或密碼錯誤!");
- return "redirect:/login";
- }
- if (currentUser.isAuthenticated()) {
- //登陸成功,保存用戶相關信息
- sessionHandle(user, request);
- //跳轉成功頁面
- return "redirect:/index";
- } else {
- redirectAttributes.addFlashAttribute("message", "用戶名或密碼錯誤!");
- return "redirect:/login";
- }
- }
-
- private void sessionHandle(User user, HttpServletRequest request) {
- HttpSession session = request.getSession();
- User loginUser = userService.getUserByLoginName(user.getLoginName());
- if(loginUser != null){
- session.setAttribute("companyId", loginUser.getCompanyId());
- session.setAttribute("username", loginUser.getNickName());
- session.setAttribute("userId", loginUser.getId());
- }
- //menuService.updateMenuInSession(request);
- }
- }
九:jsp頁面控制權限
- <%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro"%>
-
- <shiro:hasPermission name="deleteUser">
- <span id="delete" onclick="delete(this)">刪除</span>
- </shiro:hasPermission>
文末福利:
福利一:前端,Java,產品經理,微信小程序,Python等8G資源合集大放送:https://www.jianshu.com/p/e8197d4d9880
福利二:微信小程序入門與實戰全套詳細視頻教程
領取方式:
若是須要學習視頻,歡迎關注 【編程微刊】微信公衆號,回覆【領取資源】一鍵領取如下全部乾貨資源,獲取更多有用技術乾貨、文檔資料。全部文檔會持續更新,歡迎關注一塊兒成長!