您好,登錄后才能下訂單哦!
1.shiro的定義
1.1shiro的作用
認證、授權、加密、會話管理、Web集成、緩存
1.2shiro的名詞
#FormatImgID_0#
Authentication:身份認證/登錄,驗證用戶是不是擁有相應的身份
Authorization:授權,即權限 管理,驗證某個人已經登錄的人是否擁有某些權限
Session Management:會話管理,即用戶登錄后就是一次會話,在沒有退出之前所有的信息都是在會話中。。
Cryptography:加密,保護數據的安全性,密碼加密
Web Support:Web支持,可以非常容易的集成到web環境
Caching:緩存,比如用戶登錄之后,他的用戶信息,權限不必每次去查
Concurrency:shiro支持多線程應用兵法驗證,即如果在一個線程中開啟另外一個線程,權限會自動傳遞過去
Testing:提供測試支持
Run AS:允許一個用戶假裝另一個用戶(如果他們允許)的身份進行訪問
Remember Me:記住我,這是一個常見的功能,即一次登錄后,下次再來的話就不用登錄了
記住一點,Shiro不會去維護用戶、維護權限:這些需要我們自己去設計/提供,然后通過相應的接口注入給Shiro即可!
1.3shiro的架構
#FormatImgID_1#
Subject,Subject其實代表的就是當前正在執行操作的用戶,只不過因為“User”一般指代人,但是一個“Subject”可以是人,也可以是任何的第三方系統,服務賬號等任何其他正在和當前系統交互的第三方軟件系統。
所有的Subject實例都被綁定到一個SecurityManager,如果你和一個Subject交互,所有的交互動作都會被轉換成Subject與SecurityManager的交互。
SecurityManager。SecurityManager是Shiro的核心,他主要用于協調Shiro內部各種安全組件,不過我們一般不用太關心SecurityManager,對于應用程序開發者來說,主要還是使用Subject的API來處理各種安全驗證邏輯。
Realm,這是用于連接Shiro和客戶系統的用戶數據的橋梁。一旦Shiro真正需要訪問各種安全相關的數據(比如使用用戶賬戶來做用戶身份驗證以及權限驗證)時,他總是通過調用系統配置的各種Realm來讀取數據。
#FormatImgID_2#
2.SpringBoot集成shiro的步驟
2.1添加maven依賴
org.apache.shiro
shiro-core
1.4.0
org.apache.shiro
shiro-web
1.4.0
org.apache.shiro
shiro-ehcache
1.4.0
org.apache.shiro
shiro-spring
1.4.0
com.github.theborakompanioni
thymeleaf-extras-shiro
2.0.0
2.2新建緩存文件
ehcache-shiro.xml
timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false"
diskPersistent="false" diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"/>
maxElementsInMemory="10000" overflowToDisk="false" timeToIdleSeconds="0"
timeToLiveSeconds="0" statistics="true"/>
2.3重要的shiro配置類
不需要完全記住,只需要修改其中的一小部分
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator;
import org.apache.shiro.session.mgt.eis.MemorySessionDAO;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @ Author :Zgq
* @ Date :Created in 18:22 2019/6/11
* @ Description:shiro的配置類
* @ Modified By:
* @Version: $
*/
@Configuration
public class ShiroConfig {
/**
唯一需要修改的地方,有注釋
* ShiroFilterFactoryBean 處理攔截資源文件問題。
* 注意:單獨一個ShiroFilterFactoryBean配置是或報錯的,
* 因為在初始化ShiroFilterFactoryBean的時候需要注入:SecurityManager
* Filter Chain定義說明
* 1、一個URL可以配置多個Filter,使用逗號分隔
* 2、當設置多個過濾器時,全部驗證通過,才視為通過
* 3、部分過濾器可指定參數,如perms,roles
*/
@Bean
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// 必須設置 SecurityManager
shiroFilterFactoryBean.setSecurityManager(securityManager);
// 如果不設置默認會自動尋找Web工程根目錄下的"/login.jsp"頁面
//訪問的是后端url地址為 /login的接口,/未登錄頁面,會跳轉到登錄頁面
shiroFilterFactoryBean.setLoginUrl("/login");
// 登錄成功后要跳轉的鏈接
shiroFilterFactoryBean.setSuccessUrl("/index");
// 未授權界面;,基于AOP攔截,都會到登錄頁面
shiroFilterFactoryBean.setUnauthorizedUrl("/login");
// 攔截器.
Map filterChainDefinitionMap = new LinkedHashMap();
// 配置不會被攔截的鏈接 順序判斷,anon放開,不會攔截,authc會攔截
//靜態資源不能被攔截
filterChainDefinitionMap.put("/assets/**", "anon");
filterChainDefinitionMap.put("/css/**", "anon");
filterChainDefinitionMap.put("/js/**", "anon");
filterChainDefinitionMap.put("/images/**", "anon");
filterChainDefinitionMap.put("/fonts/**", "anon");
filterChainDefinitionMap.put("/login", "anon");
filterChainDefinitionMap.put("/userLogin", "anon");
// 配置退出過濾器,其中的具體的退出代碼Shiro已經替我們實現了
filterChainDefinitionMap.put("/logout", "logout");
//配置某個url需要某個權限碼
filterChainDefinitionMap.put("/hello", "perms[how_are_you]");
// 過濾鏈定義,從上向下順序執行,一般將 /**放在最為下邊
//
filterChainDefinitionMap.put("/**", "authc");
//配置記住我或認證通過可以訪問的地址
filterChainDefinitionMap.put("/index", "user");
// filterChainDefinitionMap.put("/", "user");
System.out.println("Shiro攔截器工廠類注入成功");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
/**
* 緩存
* @return
*/
@Bean
public EhCacheManager getEhCacheCache() {
EhCacheManager em = new EhCacheManager();
em.setCacheManagerConfigFile("classpath:ehcache-shiro.xml");
return em;
}
/**
* 代理
* @return
*/
@Bean
public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator daap = new DefaultAdvisorAutoProxyCreator();
daap.setProxyTargetClass(true);
return daap;
}
@Bean
public DefaultWebSessionManager getDefaultWebSessionManager() {
DefaultWebSessionManager defaultWebSessionManager = new DefaultWebSessionManager();
defaultWebSessionManager.setSessionDAO(getMemorySessionDAO());
defaultWebSessionManager.setGlobalSessionTimeout(1 * 60 * 60 * 1000);
defaultWebSessionManager.setSessionValidationSchedulerEnabled(true);
defaultWebSessionManager.setSessionIdCookieEnabled(true);
defaultWebSessionManager.setSessionIdCookie(getSimpleCookie());
return defaultWebSessionManager;
}
@Bean
public MemorySessionDAO getMemorySessionDAO() {
MemorySessionDAO memorySessionDAO = new MemorySessionDAO();
memorySessionDAO.setSessionIdGenerator(javaUuidSessionIdGenerator());
return memorySessionDAO;
}
@Bean
public JavaUuidSessionIdGenerator javaUuidSessionIdGenerator() {
return new JavaUuidSessionIdGenerator();
}
/**
* cookie對象
* @return
*/
@Bean
public SimpleCookie getSimpleCookie() {
SimpleCookie simpleCookie = new SimpleCookie();
simpleCookie.setName("security.session.id");
//
simpleCookie.setMaxAge(259200);
simpleCookie.setPath("/");
return simpleCookie;
}
/**
* cookie管理對象;
* @return
*/
/*@Bean
public CookieRememberMeManager rememberMeManager(){
System.out.println("ShiroConfiguration.rememberMeManager()");
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCookie(getSimpleCookie());
return cookieRememberMeManager;
}*/
@Bean
public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
/**
* 注入 securityManager
*/
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(
ShiroRealm shiroRealm) {
DefaultWebSecurityManager dwsm = new DefaultWebSecurityManager();
// 關聯realm.
dwsm.setRealm(shiroRealm);
//用戶授權/認證信息Cache,采用EhCache緩存
dwsm.setCacheManager(getEhCacheCache());
dwsm.setSessionManager(getDefaultWebSessionManager());
//注入記住我管理器;
/* dwsm.setRememberMeManager(rememberMeManager());*/
return dwsm;
}
@Bean
public ShiroRealm shiroRealm(EhCacheManager cacheManager) {
ShiroRealm shiroRealm = new ShiroRealm();
shiroRealm.setCacheManager(cacheManager);
return shiroRealm;
}
//開啟shiro注解支持
@Bean
public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(ShiroRealm shiroRealm){
AuthorizationAttributeSourceAdvisor aasa =new AuthorizationAttributeSourceAdvisor();
aasa.setSecurityManager(getDefaultWebSecurityManager(shiroRealm));
return aasa;
}
/**
* 配置前臺頁面thymeleaf頁面的標簽
* @return
*/
@Bean
public ShiroDialect shiroDialect() {
return new ShiroDialect();
}
}
4.核心的授權認證類
import com.example.echart.entity.Permission;
import com.example.echart.entity.Role;
import com.example.echart.entity.User;
import com.example.echart.mapper.UserRoleMapper;
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.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* @ Author :Zgq
* @ Date :Created in 18:19 2019/6/11
* @ Description:Shiro中最主要的代碼,核心代碼,用戶認證授權處
* @ Modified By:
* @Version: $
*/
public class ShiroRealm extends AuthorizingRealm {
@Autowired
private SessionDAO sessionDAO;
@Autowired
private UserRoleMapper userRoleMapper;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection auth) {
//授權
String username = (String)auth.getPrimaryPrincipal();
System.out.println("進入到授權Realm中:"+username);
List dbroleList = userRoleMapper.selectRoleList(username);
List roleList=new ArrayList();
for(Role r:dbroleList){
roleList.add(r.getCode());
}
List dbpermissions = userRoleMapper.selectPermissionList(username);
List permissionList=new ArrayList();
for(Permission p:dbpermissions){
permissionList.add(p.getPermission());
}
// roleList.add("ADMIN");
// roleList.add("USER");
// List permissionList=new ArrayList();
// permissionList.add("ADMIN:USER:UPDATA");
// permissionList.add("ADMIN:USER:DELETE");
SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
simpleAuthorizationInfo.addRoles(roleList);
simpleAuthorizationInfo.addStringPermissions(permissionList);
return simpleAuthorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
//認證
String username = (String)auth.getPrincipal();
System.out.println("進入到認證Realm中:"+username);
//在認證之前判斷當前登錄用戶,只允許一個賬號登錄
Collection sessions = sessionDAO.getActiveSessions();
for (Session session : sessions){
String loginedUsername = String.valueOf(session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY));
if(username.equals(loginedUsername)){
session.setTimeout(0);
break;
}
}
//通過username在數據庫中查詢用戶,判斷密碼
User dbuser = userRoleMapper.selectByUserName(username);
//通過用戶名在數據庫中拿到,判斷用戶名和密碼對不對
if(dbuser!=null){
SimpleAuthenticationInfo authInfo = new SimpleAuthenticationInfo(username, dbuser.getPwd(), "userRealm");
return authInfo;
}
return null;
}
}
5.登錄的Controller類,LoginController
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Map;
/**
* @ Author :Zgq
* @ Date :Created in 10:30 2019/6/12
* @ Description:登錄層方法
* @ Modified By:
* @Version: $
*/
@Controller
public class LoginController {
//登錄頁面
@RequestMapping(value = {"/login"})
public String login(Map map) {
map.put("msg","請登錄");
return "/shiro/login-page";
}
//登錄成功頁面
@RequestMapping(value = {"/index"})
public String index(Map map) {
map.put("msg","登錄成功");
//獲取用戶信息
Subject subject = SecurityUtils.getSubject();
String username = (String)subject.getPrincipal();
map.put("username",username);
return "/shiro/index";
}
//登錄請求
@RequestMapping(value = {"/userLogin"})
public String userLogin(String username, String pwd,boolean rememberMe, Map map)
{無錫人流醫院 http://xmobile.wxbhnk120.com/
Subject subject = SecurityUtils.getSubject();
//根據自己鹽加密的方式,放入密碼
String encodePwd = new Md5Hash(pwd, username).toString();
UsernamePasswordToken auth = new UsernamePasswordToken(username, encodePwd,rememberMe);
try {
subject.login(auth);
return "redirect:/index";
}catch (Exception e){
e.printStackTrace();
map.put("msg","賬號或密碼錯誤");
return "redirect:/login";
}
}
//退出登錄
@RequestMapping(value = {"/loginOut"})
public String loginOut(Map map) {
//獲取用戶信息
Subject subject = SecurityUtils.getSubject();
subject.logout();
map.put("msg","退出登錄");
return "redirect:/login";
}
/**
* 加密的測試
* @param args
*/
public static void main(String[] args) {
//加密
String zhouguoqing = new Md5Hash("111", "admin1").toString();
System.out.println(zhouguoqing);
}
}
6.因為是和數據庫直接對接的,所以我也新建了一個UserRoleMapper接口,返回數據
import com.example.echart.entity.Permission;
import com.example.echart.entity.Role;
import com.example.echart.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;
import java.util.List;
@Mapper
@Component
public interface UserRoleMapper {
/**
* 通過登錄名查詢信息
* @param username
* @return
* @throws Exception
*/
@Select("select * from t_user where username=#{username} limit 1")
User selectByUserName(String username);
/**
* 通過用戶名查詢用戶角色信息
* @param username
* @return
* @throws Exception
*/
@Select("select * from t_user u,t_role r,t_user_role ur where u.username=#{username} and ur.userId=u.id and ur.roleId=r.id")
List selectRoleList(String username);
/**
* 通過用戶名查找用戶權限
* @param username
* @return
*/
@Select("select * from t_permission p \n" +
"where p.id in(\n" +
"\tselect permissionId from t_role_permission rp \n" +
"\twhere rp.roleId in (\n" +
"\t\t\tselect ur.roleId from t_user_role ur where userId in(\n" +
"\t\t\tselect u.id from t_user u where u.username=#{username}\n" +
"\t\t\t)\n" +
"\t)\n" +
")")
List selectPermissionList(String username);
}
7.前臺頁面thymeleaf的展示
xmlns:shiro="http://www.w3.org/1999/xhtml">
你好:
ADMIN角色
USER角色
SUPERMAN角色
UPDATA權限
DELETE權限
INSERT權限
SELECT權限
3.完成的效果
#FormatImgID_3#
用不同用戶登錄之后會自動獲取登錄用戶的角色和權限信息
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。