真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

SpringBoot集成Shiro安全框架

1.shiro的定義

成都創(chuàng)新互聯(lián)公司專注于太倉企業(yè)網(wǎng)站建設(shè),響應(yīng)式網(wǎng)站建設(shè),成都商城網(wǎng)站開發(fā)。太倉網(wǎng)站建設(shè)公司,為太倉等地區(qū)提供建站服務(wù)。全流程按需設(shè)計(jì)網(wǎng)站,專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,成都創(chuàng)新互聯(lián)公司專業(yè)和態(tài)度為您提供的服務(wù)

1.1shiro的作用

認(rèn)證、授權(quán)、加密、會話管理、Web集成、緩存

1.2shiro的名詞

#FormatImgID_0#

Authentication:身份認(rèn)證/登錄,驗(yàn)證用戶是不是擁有相應(yīng)的身份

Authorization:授權(quán),即權(quán)限 管理,驗(yàn)證某個(gè)人已經(jīng)登錄的人是否擁有某些權(quán)限

Session Management:會話管理,即用戶登錄后就是一次會話,在沒有退出之前所有的信息都是在會話中。。

Cryptography:加密,保護(hù)數(shù)據(jù)的安全性,密碼加密

Web Support:Web支持,可以非常容易的集成到web環(huán)境

Caching:緩存,比如用戶登錄之后,他的用戶信息,權(quán)限不必每次去查

Concurrency:shiro支持多線程應(yīng)用兵法驗(yàn)證,即如果在一個(gè)線程中開啟另外一個(gè)線程,權(quán)限會自動傳遞過去

Testing:提供測試支持

Run AS:允許一個(gè)用戶假裝另一個(gè)用戶(如果他們允許)的身份進(jìn)行訪問

Remember Me:記住我,這是一個(gè)常見的功能,即一次登錄后,下次再來的話就不用登錄了

記住一點(diǎn),Shiro不會去維護(hù)用戶、維護(hù)權(quán)限:這些需要我們自己去設(shè)計(jì)/提供,然后通過相應(yīng)的接口注入給Shiro即可!

1.3shiro的架構(gòu)

#FormatImgID_1#

Subject,Subject其實(shí)代表的就是當(dāng)前正在執(zhí)行操作的用戶,只不過因?yàn)椤癠ser”一般指代人,但是一個(gè)“Subject”可以是人,也可以是任何的第三方系統(tǒng),服務(wù)賬號等任何其他正在和當(dāng)前系統(tǒng)交互的第三方軟件系統(tǒng)。

所有的Subject實(shí)例都被綁定到一個(gè)SecurityManager,如果你和一個(gè)Subject交互,所有的交互動作都會被轉(zhuǎn)換成Subject與SecurityManager的交互。

SecurityManager。SecurityManager是Shiro的核心,他主要用于協(xié)調(diào)Shiro內(nèi)部各種安全組件,不過我們一般不用太關(guān)心SecurityManager,對于應(yīng)用程序開發(fā)者來說,主要還是使用Subject的API來處理各種安全驗(yàn)證邏輯。

Realm,這是用于連接Shiro和客戶系統(tǒng)的用戶數(shù)據(jù)的橋梁。一旦Shiro真正需要訪問各種安全相關(guān)的數(shù)據(jù)(比如使用用戶賬戶來做用戶身份驗(yàn)證以及權(quán)限驗(yàn)證)時(shí),他總是通過調(diào)用系統(tǒng)配置的各種Realm來讀取數(shù)據(jù)。

#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 處理攔截資源文件問題。

* 注意:單獨(dú)一個(gè)ShiroFilterFactoryBean配置是或報(bào)錯(cuò)的,

* 因?yàn)樵诔跏蓟疭hiroFilterFactoryBean的時(shí)候需要注入:SecurityManager

* Filter Chain定義說明

* 1、一個(gè)URL可以配置多個(gè)Filter,使用逗號分隔

* 2、當(dāng)設(shè)置多個(gè)過濾器時(shí),全部驗(yàn)證通過,才視為通過

* 3、部分過濾器可指定參數(shù),如perms,roles

*/

@Bean

public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {

ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

// 必須設(shè)置 SecurityManager

shiroFilterFactoryBean.setSecurityManager(securityManager);

// 如果不設(shè)置默認(rèn)會自動尋找Web工程根目錄下的"/login.jsp"頁面

//訪問的是后端url地址為 /login的接口,/未登錄頁面,會跳轉(zhuǎn)到登錄頁面

shiroFilterFactoryBean.setLoginUrl("/login");

// 登錄成功后要跳轉(zhuǎn)的鏈接

shiroFilterFactoryBean.setSuccessUrl("/index");

// 未授權(quán)界面;,基于AOP攔截,都會到登錄頁面

shiroFilterFactoryBean.setUnauthorizedUrl("/login");

// 攔截器.

Map filterChainDefinitionMap = new LinkedHashMap();

// 配置不會被攔截的鏈接 順序判斷,anon放開,不會攔截,authc會攔截

//靜態(tài)資源不能被攔截

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已經(jīng)替我們實(shí)現(xiàn)了

filterChainDefinitionMap.put("/logout", "logout");

//配置某個(gè)url需要某個(gè)權(quán)限碼

filterChainDefinitionMap.put("/hello", "perms[how_are_you]");

// 過濾鏈定義,從上向下順序執(zhí)行,一般將 /**放在最為下邊

//

filterChainDefinitionMap.put("/**", "authc");

//配置記住我或認(rèn)證通過可以訪問的地址

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();

// 關(guān)聯(lián)realm.

dwsm.setRealm(shiroRealm);

//用戶授權(quán)/認(rèn)證信息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頁面的標(biāo)簽

* @return

*/

@Bean

public ShiroDialect shiroDialect() {

return new ShiroDialect();

}

}

4.核心的授權(quán)認(rèn)證類

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中最主要的代碼,核心代碼,用戶認(rèn)證授權(quán)處

* @ Modified By:

* @Version: $

*/

public class ShiroRealm extends AuthorizingRealm {

@Autowired

private SessionDAO sessionDAO;

@Autowired

private UserRoleMapper userRoleMapper;

@Override

protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection auth) {

//授權(quán)

String username = (String)auth.getPrimaryPrincipal();

System.out.println("進(jìn)入到授權(quán)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 {

//認(rèn)證

String username = (String)auth.getPrincipal();

System.out.println("進(jìn)入到認(rèn)證Realm中:"+username);

//在認(rèn)證之前判斷當(dāng)前登錄用戶,只允許一個(gè)賬號登錄

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在數(shù)據(jù)庫中查詢用戶,判斷密碼

User dbuser = userRoleMapper.selectByUserName(username);

//通過用戶名在數(shù)據(jù)庫中拿到,判斷用戶名和密碼對不對

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)

{無錫人流醫(yī)院 http://xmobile.wxbhnk120.com/

Subject subject = SecurityUtils.getSubject();

//根據(jù)自己鹽加密的方式,放入密碼

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","賬號或密碼錯(cuò)誤");

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.因?yàn)槭呛蛿?shù)據(jù)庫直接對接的,所以我也新建了一個(gè)UserRoleMapper接口,返回?cái)?shù)據(jù)

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);

/**

* 通過用戶名查找用戶權(quán)限

* @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權(quán)限

DELETE權(quán)限

INSERT權(quán)限

SELECT權(quán)限

3.完成的效果

#FormatImgID_3#

用不同用戶登錄之后會自動獲取登錄用戶的角色和權(quán)限信息


本文題目:SpringBoot集成Shiro安全框架
轉(zhuǎn)載來源:http://weahome.cn/article/ijodss.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部