web專案整合shiro
一、shiro介紹
借用官方的話:Apache Shiro是一個功能強大、易於使用的Java安全框架,它常用於身份驗證、授權、加密和會話管理。Shiro的API易於理解,您可以快速輕鬆地保護任何應用程式——從小的移動應用程式到大的Web和企業應用程式。
二、spring boot整合shiro
1.maven資源
我使用的版本是1.4.0
<!--shiro --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>${shiro.version}</version> </dependency>
2.shiroConfig 配置類:註釋很詳細,緩衝如果不需要可以不要,shiro預設有一套快取規則。
package com.cn.iris.common.config; import com.cn.iris.common.core.shiro.LoginRealm; import org.apache.shiro.authc.credential.CredentialsMatcher; import org.apache.shiro.authc.credential.SimpleCredentialsMatcher; import org.apache.shiro.cache.CacheManager; import org.apache.shiro.cache.ehcache.EhCacheManager; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.cache.ehcache.EhCacheManagerFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.LinkedHashMap; import java.util.Map; /** * Author: IrisNew * Description: shiro 配置 * Date: 2018/6/6 16:45 */ @Configuration public class ShiroConfig { /** * 快取管理器 使用Ehcache實現 */ @Bean public CacheManager getCacheShiroManager(EhCacheManagerFactoryBean ehcache) { EhCacheManager ehCacheManager = new EhCacheManager(); ehCacheManager.setCacheManager(ehcache.getObject()); return ehCacheManager; } /** * ShiroFilterFactoryBean 處理攔截資原始檔問題 * 初始化ShiroFilterFactoryBean的時候需要注入:SecurityManager * */ @Bean(name = "shiroFilter") public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") SecurityManager securityManager){ ShiroFilterFactoryBean sfbBean = new ShiroFilterFactoryBean(); sfbBean.setSecurityManager(securityManager); //設定預設登陸頁 sfbBean.setLoginUrl("/welcome"); //登陸成功後跳轉的url sfbBean.setSuccessUrl("/index"); //設定許可權不足跳轉 sfbBean.setUnauthorizedUrl("/403"); //自定義過濾器 /*Map<String, Filter> filters=new HashMap<>(); filters.put("per",getPermissionFilter()); filters.put("verCode",getVerfityCodeFilter()); sfbBean.setFilters(filters);*/ /** 配置訪問許可權 * 過濾鏈定義,從上向下順序執行,一般將/**放在最為下邊 * anon 不需要認證 * authc 需要認證 */ Map<String, String> filterMap = new LinkedHashMap<>(); filterMap.put("/css/**","anon"); filterMap.put("/js/**","anon"); filterMap.put("/welcome","anon"); filterMap.put("/userlogin","anon"); filterMap.put("/getVeCode","anon"); filterMap.put("/logout","logout"); filterMap.put("/plugin/**","anon"); filterMap.put("/**","authc"); sfbBean.setFilterChainDefinitionMap(filterMap); return sfbBean; } // 配置核心安全事務管理器 @Bean(name = "securityManager") public SecurityManager securityManager(@Qualifier("loginRealm") LoginRealm loginRealm,CacheManager cacheShiroManager) { DefaultWebSecurityManager manager = new DefaultWebSecurityManager(); //自定義的許可權登入器 manager.setRealm(loginRealm); //自定義的session管理器 // manager.setSessionManager(sessionManager); //自定義快取策略 manager.setCacheManager(cacheShiroManager); return manager; } //配置自定義的許可權登入器 @Bean(name = "loginRealm") public LoginRealm getLoginRealm(){ LoginRealm realm= new LoginRealm(); realm.setCredentialsMatcher(credentialsMatcher()); return realm; } // 配置自定義的密碼匹配比較器 @Bean(name = "credentialsMatcher") public CredentialsMatcher credentialsMatcher() { return new SimpleCredentialsMatcher(); } /** * 啟用shrio授權註解攔截方式,AOP式方法級許可權檢查 */ @Bean public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(@Qualifier("securityManager") SecurityManager securityManager){ AuthorizationAttributeSourceAdvisor as=new AuthorizationAttributeSourceAdvisor(); as.setSecurityManager(securityManager); return as; } }
3.自定義Realm,這個是所有用shiro都需要自定義的。
其中userServiceImpl的findByAcc方法是用賬號查詢使用者實體返回;
role2menuService的getMenuCodesByRoleIds方法是用來查詢角色對應的所有選單及增刪改查許可權的。
package com.cn.iris.common.core.shiro; import com.cn.iris.admin.entity.User; import com.cn.iris.admin.service.IRole2menuService; import com.cn.iris.admin.service.IUserService; import org.apache.shiro.authc.*; 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 org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; /** * Author: IrisNew * Description: shiro許可權登入器 * Date: 2018/6/8 16:14 */ @Service public class LoginRealm extends AuthorizingRealm { @Autowired private IUserService userServiceImpl; @Autowired private IRole2menuService role2menuService; // 認證.登入 提供賬戶資訊返回認證資訊 /** * 當呼叫如下程式碼時會進入這個方法(一般是登入頁面) * Subject currentUser = SecurityUtils.getSubject(); * currentUser.login(token); */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; // 獲取使用者輸入的token //輸入的使用者名稱 String userAcc = token.getUsername(); User user = userServiceImpl.findByAcc(userAcc); if (user == null) { throw new UnknownAccountException("賬號或者密碼錯誤!"); } return new SimpleAuthenticationInfo(user, user.getUserPsw(), getName()); } // 授權 // 提供使用者資訊返回許可權資訊 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { // 獲取session中的使用者 User user = (User) principalCollection.getPrimaryPrincipal(); List<String> roIdsList = user.getRoleIds(); List<String> permissionsList = role2menuService.getMenuCodesByRoleIds(roIdsList); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); info.addRoles(roIdsList); if(permissionsList != null && permissionsList.size()>0){ info.addStringPermissions(permissionsList); // 將許可權放入shiro中. } return info; } }
4.工具類,方便獲取當前登陸的session及Subject物件。
package com.cn.iris.common.core.shiro;
import com.cn.iris.admin.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
/**
* Author: IrisNew
* Description:shiro工具類
* Date: 2018/6/11 14:48
*/
public class ShiroUtil {
/**
* 獲取當前 Subject
*/
public static Subject getSubject(){
return SecurityUtils.getSubject();
}
/**
* 獲取登陸使用者
*/
public static User getUser(){
return (User)getSubject().getPrincipals().getPrimaryPrincipal();
}
/**
* 驗證使用者是否屬於某角色
*/
public boolean hasRole(String roleName) {
return getSubject() != null && roleName != null && roleName.length() > 0 && getSubject().hasRole(roleName);
}
/**
* 驗證使用者是否擁有指定許可權
*/
public boolean hasPermission(String permission) {
Subject subject = getSubject();
return getSubject() != null && permission != null
&& permission.length() > 0
&& getSubject().isPermitted(permission);
}
public static Session getSession(){
return getSubject().getSession();
}
}
5.登陸及登出呼叫(程式碼段)
@GetMapping("/userlogin")
public String index(HttpServletRequest request, String userAcc, String userPsw) {
Subject subject = ShiroUtil.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(userAcc.trim(),userPsw);
subject.login(token);
User user = userServiceImpl.findByAcc(userAcc);
if(user.getUserPsw().equals(userPsw)){
logger.info("使用者登陸:"+user.getNickName());
return "redirect:/index";
}
return "login";
}
//跳轉至登陸頁
@GetMapping("/logOut")
public String logOut() {
ShiroUtil.getSubject().logout();
return "/login";
}
前端頁面就不將程式碼貼出來了。
我本人的自己寫了個簡單的springboot專案,整合了shiro,是一套完整的專案管理類專案,開源免費。
感興趣的可以看看:Iris-開源的後臺管理類專案;希望能高臺貴手,給小弟一個star.感謝!
相關推薦
web專案整合shiro
一、shiro介紹 借用官方的話:Apache Shiro是一個功能強大、易於使用的Java安全框架,它常用於身份驗證、授權、加密和會話管理。Shiro的API易於理解,您可以快速輕鬆地保護任何應用程式——從小的移動應用程式到大的Web和企業應用程式。 二、sprin
web專案整合shiro後加入tomcat啟動超時,tomcat無法正常啟動
1:問題出現緣由 web專案許可權框架使用shiro,在和單點登入整合後,登入login添加了一些判斷,如下: Object authUser=UserUtils.getShiroSession().getAttribute("self_login_check"); if(
shiro許可權框架詳解06-shiro與web專案整合(下)
shiro和web專案整合,實現類似真實專案的應用 web專案中認證 web專案中授權 shiro快取 sessionManager使用 驗證碼功能實現 記住我功能實現 web專案中認證 實現方式 修改CustomRealm 的 doGe
shiro許可權框架詳解06-shiro與web專案整合(上)
shiro和web專案整合,實現類似真實專案的應用 本文中使用的專案架構是springMVC+mybatis,所以我們是基於搭建好的專案進行改造的。 將shiro整合到web應用中 登入 退出 認證資訊在頁面展現,也就是顯示選單 shiro的過濾器
ssm框架的maven web專案整合redis服務
一、Linux下redis的安裝 單檯安裝,測試用 開啟https://redis.io/download,往下翻,Installation ,有詳細的安裝、啟動和簡單測試的命令 二、整合redis服務 下面就是在study專案中整合redis服務(根據自己的專案進行相應的修改):
Spring與Web專案整合的原理
引言: 在剛開始我們接觸IOC時,我們載入並啟用SpringIOC是通過如下程式碼手動載入 applicationContext.xml 檔案,new出context物件,完成Bean的建立和屬性的注入。 public class TestIOC { @Test public
web專案整合spring框架
以下是一個最簡單的示例 1、新建一個標準的javaweb專案 2、匯入spring所需的一些基本的jar包 3、配置web.xml檔案 <?xml version="1.0" encoding="UTF-8"?> <web-app ver
Axis2與Web專案整合及Axis2在Web專案中整合Spring
Axis2簡介: Axis2是一套嶄新的WebService引擎,該版本是對Axis1.x重新設計的產物。Axis2不僅支援SOAP1.1和SOAP1.2,還集成了非常流行的REST WebService,同時還支援spring、JSON等技術。
【SSM】Eclipse使用Maven建立Web專案+整合SSM框架
自己接觸ssm框架有一段時間了,從最早的接觸新版ITOO專案的(SSM/H+Dobbu zk),再到自己近期來學習到的《淘淘商城》一個ssm框架的電商專案。用過,但是還真的沒有自己搭建過,一直都是用別人搭建好的。所以,從網上找了一些材料,結合自己來解決過程
SSH專案整合Shiro @RequiresPermissions後@Autowired註解自動注入失敗
在做專案的時候整合了shiro進行許可權驗證的時候,使用@RequiresPermissions後@Autowired註解自動注入失敗,導致注入Service時為null,記錄一下解決方案。 步驟: a. 給UserServiceImpl指定id @Serv
shiro學習:shiro整合SpringMVC的web專案
這篇文章只是介紹了shiro與springweb專案進行的整合,並沒有涉及到認證的實現,如果您需要認證的相關實現,請看下我的下一篇:Shiro實現登入和退出 一、準備環境 與其它java開源框架類似,將shiro的jar包加入專案就可以使用shiro提供的功能了。shi
web專案shiro與spring整合 maven依賴及web配置詳解
依賴shiro的maven座標: <dependency> <groupId>org.apache.shiro</groupId> <artifa
Shiro許可權控制框架 ---SpringMVC+Spring+My batis+Mysql+Maven整合開發Web專案
在之前的博文簡單的介紹shiro許可權控制框架,現在我們接著講解使用 SpringMVC+Spring+My batis+Mysql+Maven整合開發Web專案 1.先由Maven選擇MavenProject建立一個Web專案(如果你還不會使用Maven的話可以去看
Shiro與基本web環境整合登陸驗證實例
erro pri void sta map -name -- role uid 1. 用maven導入Shiro依賴包 <dependency> <groupId>org.apache.shiro</groupId>
web項目整合Shiro框架
dtd con ron package ini 認證 utf ide -type 1、修改pom.xml文件 <dependency> <groupId>org.apache.shiro</groupId>
tomcat與IDEA整合&建立一個web專案
最近使用IDEA跑J2EE,順便寫一些入門教程,方便學習使用IDEA。 一、配置Tomcat到Idea中 首先點選run--Edit... 然後展開defaults
springboot專案,thymeleaf整合shiro
github地址:https://github.com/theborakompanioni/thymeleaf-extras-shiro ps:此文章需要相應的shiro基礎,內容很精簡 1.pom.xml <properties> <project.
springboot+shiro+redis專案整合
springboot+shiro+redis專案整合 介紹: Apache Shiro是一個強大且易用的Java安全框架,執行身份驗證、授權、密碼學和會話管理。使用Shiro的易於理解的API,您可以快速、輕鬆地獲得任何應用程式,從最小的移動應用程式到最大的網路和企業應用程式。(摘自
spring boot2.0+shiro+mybatis多資料來源+druid連線池專案整合
關於整合 網上關於springboot2.0和shiro+myabtis整合的案例很少,大神的教程也是用jpa編寫,jpa很方便,但是還有很多人用mybatis,加之剛學習完mybatis多資料來源整合和druid連線池監控配置,所以算是階段性記錄。 專案目
Tomcat+solrcloud6.2版本整合Web專案
solrcloud