시로
Apache Shiro는 가벼운 인증 및 승인 프레임 워크입니다. 스프링 보안과 비교할 때 간단하고 사용하기 쉽고 유연성이 높습니다. SpringBoot 자체는 결국 보안 지원을 제공합니다. 결국 고유 한 것입니다. SpringBoot는 시로를 당분간 통합하지 않으므로 직접 일치시켜야합니다.
1. 종속성 추가
<pectionency> <groupid> org.apache.shiro </groupid> <artifactid> shiro-spring </artifactid> <bersion> 1.2.5 </version> </dependency> <prectionency> <groupid> org.apache.shiro </groupid> <artifactid> shiro-ehcache> </version> 1.5 </version> 1.5.
2. Shiro 구성 클래스를 쓰십시오
패키지 com.xbz.web.system.config; import at.pollux.thymeleaf.shiro.dialect.shirodialect; import org.apache.shiro.authc.credential.credentialsmatcher; import org.apache.shiro.authc.credential.hashedcredentialsmatcher; import org.apache.shiro.cache.ehcache.ehcachemanager; import org.apache.shiro.codec.base64; import org.apache.shiro.session.sessionlistener; import org.apache.shiro.session.mgt.sessionmanager; import org.apache.ship.session.mgt.eis.memorysessiondao; import org.apache.ship.session.mgt.eis.sessiondao; 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; org.springframework.aop.framework.autoproxy.defaultAdvisorAutoProxycreator; org.springframework.boot.autoconfigure.condition.condition.conditionalonmissingbean; import org.springframework.context.annotation.bean; org.springframework.context.annotation.configuration; org.springframework.context.annotation.dependson; java.util.arraylist 가져 오기; java.util.collection import; java.util.linkedhashmap import; java.util.map import; /*** Shiro 구성 클래스* Apacheshiro Core는 SpringMVC가 DispachServlet을 사용하여 요청 배포를 제어하는 것처럼 필터를 통한 권한 제어 및 차단을 구현합니다. * 필터, 즉 URL 규칙을 통한 필터링 및 권한 검증을 사용하고 있으므로 URL에 대한 일련의 규칙 및 액세스 권한을 정의해야합니다.* / @Configuration Public Class ShiroConfiguration { / *** DefaultAdvisorAutoProxycreator, Spring의 BEAN 및 ASOP 대량의 메소드 클래스를 결정합니다. */ @bean @bean @conditionalonmissingbean public defaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator () {defaultAdvisorAutoProxyCreator defaultaap = 새로운 defaultAdvisorAutoProxyCreator (); defaultaap.setproxytargetClass (true); 반환 defaultaap; } /*** ShirofilterFactoryBean : Shirofilter를 생성하기 위해 리소스 파일을 가로 채지 마십시오. * 주로 SecurityManager, 필터, FilterChainDefinitionManager의 세 가지 항목을 유지합니다. * 참고 : 단일 shirofilterfactorybean 구성은 ShiroFilterFactoryBean을 초기화 할 때 SecurityManager * * FilterChain 정의 설명 * 1을 주입해야하기 때문에 오류가 발생하거나보고합니다. URL은 Commas로 분리 된 여러 필터를 구성 할 수 있습니다. perms, 역할 */ @bean public shirofilterfactorybean shirofilterfactorybean () {shirofilterfactorybean shirofilterfactorybean = new shirofilterfactorybean (); shirofilterFactoryBean.SetSecurityManager (securityManager ()); shirofilterFactoryBean.setLoginUrl ( "/login"); // 웹 프로젝트의 루트 디렉토리에서 로그인 .jsp 페이지를 설정하지 마십시오. ShiroFilterFactoryBean.setSuccessurl ( "/index"); // 로그인 후 점프 연결이 성공적입니다. // 여러 필터의 사용자 정의 인터셉터 설정*// map <String, 필터> 필터 = 새로운 LinkedHashMap <> (); // logoutFilter logoutFilter = new logoutFilter (); // 동시에 동일한 계정의 온라인 번호를 제한합니다. 또는 단일 사인온 등 // logoutFilter.setRedirectUrl ( "/login"); // 필터 .put ( "로그 아웃", null); // shirofilterFactoryBean.setFilters (필터); Map <String, String> FilterChainDefinitionMap = New LinkedHashMap <> (); // filterChainDefinitionManager는 링크드 하쉬 맵이어야합니다. // 다른 디렉토리 (예 : JS, IMG 등) 및 FilterChainDefinitionMap.put ( "/", "anon")에 파일이있는 경우 정적 자원이 권한이 필요하지 않습니다. FilterChainDefinitionMap.put ( "/login", "anon"); // URL FilterChainDefinitionMap.put의 일부를 구성합니다 ( "/logout", "logout"); FilterChainDefinitionMap.put ( "/user/**", "authc, 역할 [role_user]"); // 사용자는 액세스 할 수있는 역할 _USER 역할입니다. 사용자 역할은 사용자 행동을 제어합니다. FilterChainDefinitionMap.put ( "/events/**", "authc, 역할 [role_admin]"); // filterChainDefinitionMap.put ( "/user/edit/**", "authc, perms [user : edit]"); // 테스트의 경우 죽은 값이 고정되어 있으며 데이터베이스 또는 기타 구성에서도 읽을 수도 있습니다. 여기서 권한은 FilterChainDefinitionMap.put ( "/**", "authc")을 제어하는 데 사용됩니다. // 로그인 해야하는 리소스, 일반적으로 /** 하단에 /**를 바닥 shirofilterfactoryBean.setFilterChainDefinitionMap (FilterChainDefinitionMap); 반환 shirofilterfactorybean; } // 지역 쿠키 및 세션 // ========================== 쿠키 및 세션 관리 시작 ===================== 개인 정적 최종 문자열 cookie_name = "RememberMe"; /** 쿠키 객체 관리*/public simplecookie regreammecookie () {//이 매개 변수는 쿠키의 이름이며, 프론트 엔드의 확인란의 이름에 해당합니다. simplecookie.setmaxage (604800); // 내 쿠키가 7 일 동안 효력을 발휘하고 장치가 Simplecookie로 반환되었습니다. } / ** 쿠키 관리 객체 : 기억을 기억하십시오. CookierememberMemanager.setCookie (RememberMeCookie ()); COORIEREMEMBERMEMANAGER.SETCIPHERKEY (Base64.Decode ( "3AVVHMFLUS0KTA3KPRSDAG =="); // 기억 쿠키 암호화 키는 각 항목이 다른 기본 AES 알고리즘 키 길이 (128 256 512 비트) 리턴 쿠키 오블 메마너를 제안합니다. } @bean sessiondao sessiondao () {return new MemorySessionDao (); } @Bean public sessionManager sessionManager () {defaultWebsessionManager SessionManager = 새 DefaultWebsessionManager (); Collection <SessionListener> 리스너 = New ArrayList <> (); Listeners.add (new bdsessionListener ()); SessionManager.SetSessionListEners (리스너); SessionManager.setSessionDao (sessionDao ()); 반품 세션 관리자; } // ================================================================= /*** 보안 관리자 : 핵심 보안 거래 관리자, 허가 관리*이 클래스는 로그인, 로그 아웃, 허가 및 세션 처리를 결합합니다. 비교적 중요한 수업입니다. */ @bean (name = "securityManager") public defaultWebSecurityManager SecurityManager () {defaultWebSecurityManager SecurityManager = 새 DefaultWebSecurityManager (); SecurityManager.setRealm (shirorealm ()); SecurityManager.setCacheManager (ehcacheManager ()); //// ehcache cache를 사용하는 사용자 인증/인증 정보 캐시 // 사용자 정의 세션 관리를 사용합니다. // 내 관리자를 기억하십시오. SecurityManager.setRememberMemanager (RememberMemanager ()); 반품 보안 관리자; } /** * Shirorealm, 이것은 사용자 인증 및 권한 처리를 담당하는 Realm 인증에서 상속 된 사용자 정의 인증 클래스입니다. JDBCREALM의 구현을 참조 할 수 있습니다. */ @bean @dependson ( "LifeCycleBeanPostProcessor") Public Shirorealm Shirorealm (CredentialSmatcher Matcher) {Shirorealm Realm = New Shirorealm (); RealM.SetCredentialSmatcher (매치 자); // 비밀번호 검증을 구현하면 리턴 영역; } /*** ehcachemanager, cachemanager* 사용자가 성공적으로 로그인 한 후 사용자 정보 및 권한 정보를 캐시하고 사용자가 요청할 때마다 사용자 세션에 넣습니다. 이 Bean이 설정되지 않으면 각 요청에 대해 데이터베이스가 한 번 쿼리됩니다. */ @bean @dependson ( "LifeCycleBeanPostProcessor") public ehcachemanager ehcachemanager () {ehcachemanager em = new ehcachemanager (); Em.setCachemanagerConfigfile ( "classpath : config/ehcache.xml"); // 구성 파일 경로 반환 EM; } /** * LifeCycleBeanPostProcessor, 이것은 DestructionAwareBeanPostProcessor의 서브 클래스입니다. * *는 org.apache.shiro.util.initializable 유형 Bean의 수명주기를 담당합니다. * 주로 EhcacheManager 클래스뿐만 아니라 Realm 클래스를 승인하는 서브 클래스입니다. */ @Bean (이름 = "LifeCycleBeanPostProcessor") Public LifeCycleBeanPostProcessor LifeCycleBeanPostProcessor () {새로운 LifeCycleBeanPostProcessor (); } /** * HashedCredentialSmatcher,이 클래스는 비밀번호를 인코딩하는 것입니다. * 비밀번호가 데이터베이스에 명확하게 저장되는 것을 방지합니다. 물론, 인증에 로그인 할 때, *이 클래스는 양식 * 처리 인증 일치 프로세서에서 입력 한 암호를 인코딩하는 데 책임이 있습니다. 사용자 정의가 해시 크레디언스 매칭 */ @bean의 상속이 필요한 경우 (name = "hashedcredcredectementsmatcher"public hashedcredectementsmatcher () CredentialSmatcher = New HashedCredentialSmatcher (); CredentialSmatcher.SethashalGorithmname ( "MD5"); // 암호화 메소드를 지정하면 여기에 캐시를 추가 할 수도 있습니다. 사용자가 5 개 이상의 로그인 오류를 로그인하면 사용자가 잠겨 있습니다. 사용자는 끊임없이 CredentialSmatcher.sethisterations (2)를 로그인하려고하지 않습니다. CredentialSmatcher.SetStoredCredentialShexEncoded (true); Return CredentialSmatcher; } /** * Shiro에서 구현 된 고문 클래스 인 AuthorizationAttributesourceAdvisor * * aopallianceannotationsauthorizingMethodinterceptor를 내부적으로 사용하여 다음 주석과 메소드를 차단합니다. */ @bean public authorizationAttributesOURCEADvisor 인증 attributesourceadvisor () {authorizationAttributesourceAdvisor advisor = new AuthorizationAttributeSourceadvisor (); Advisor.SetSecurityManager (SecurityManager ()); 반환 고문; } // @bean public shirodialect shirodialect () {return new shirodialect (); }} 3. 영역 검증 클래스를 사용자 정의합니다
패키지 com.yiyun.web.system.config; com.yiyun.dao.master.userdao 가져 오기; import com.yiyun.domain.userdo; com.yiyun.web.common.utils.shiroutils import; com.yiyun.web.system.service.menuservice import; import org.apache.shiro.securityutils; 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.session.session; import org.apache.shiro.subject.principalcollection; org.springframework.beans.factory.annotation.autowired; java.util.*; / *** 사용자 역할 및 허가 정보 가져 오기*/ 공개 클래스 Shirorealm은 REALM을 승인합니다. @autowired 개인 메뉴 서비스 메뉴 서비스; /*** 로그인 인증은 일반적으로 로그인 한 후 현재 사용자에게 권한이 부여됩니다. 이 단계는 dogetauthenticationinfo를 기반으로합니다. 사용자 정보 후에 만 사용자의 역할 및 승인 정보를 기반으로 사용자를 승인할지 여부를 결정할 수 있습니다. 따라서 여기서는 여기서의 역할과 권한은 사용자 * @param authenticationtoken * @return * @throws authenticationException */ @override protected authenticationInfo dogetauthenticationInfo (authenticaticToken authenticationToken) authenticationException {usernamepasswordtoken token = (usernamepassokentoken =); userdo user = usermapper.findbyname (token.getusername ()); //이 사용자가 있는지 확인하십시오. Shiro는 미국 목록에 대한 비밀번호 비교 및 검증을 수행합니다. <urole> rlist = uroledao.findrolebyuid (user.getid ()); // 사용자 역할 목록 <upermission> plist = upermissiondao.findpermissionbyuid (user.getid ()); // rolestrlist = new arraylist <///////4 rolistlist = new arraylist </// list <string> herraylist = new arraylist <string> (); /// 사용자의 권한 수집 (urole 역할 : rlist) {rolestrlist.add (role.getName ()); } for (upermission upermission : plist) {perminsstrlist.add (upermission.getname ()); } user.setRolestRlist (rolestRlist); user.setperminsstrlist (perminsstrlist); 세션 세션 = securityUtils.getSubject (). getsession (); session.setattribute ( "사용자", 사용자); // 성공하면 세션에 넣으십시오 // 존재하는 경우이 사용자를 로그인 인증 정보에 저장하면 비밀번호를 직접 비교할 필요가 없습니다. Shiro는 우리를 위해 비밀번호 비교 확인을 수행합니다. 새로운 simpleAuthenticationInfo를 반환합니다 (user, user.getpassword (), getName ()); } return null; } /** * Permission authentication* Get the user's permission information, which is to make judgments for the next step of authorization, to obtain the current user's role and the permission information owned by these roles* @param principalCollection * @return */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { // Get the user name entered in the current login, which is (String) PrincipalCollection.fromRealm (getName ()). iterator (). next ()에 해당합니다. // 문자열 loginName = (String) super.getAvailablePrincipal (PrincipalCollection); userdo user = (userdo) principalCollection.getPrimaryPrincipal (); // // 데이터베이스로 이동 하여이 개체가 있는지 확인하십시오. // 사용자 user = null; // 실제 프로젝트에서 실제 상황에 따라 캐시 할 수 있습니다. 그렇지 않은 경우 Shiro 자신은 시간 간격 메커니즘을 가지고 있으며 2 분 이내에 메소드를 반복적으로 실행하지 않습니다. if (user! = null) {// 권한 정보 객체 정보는 찾은 사용자 simpleAuthorizationInfo의 모든 역할 (역할) 및 권한 (허가)을 저장하는 데 사용됩니다. // 사용자의 역할 수집 정보 addroles (user.getRolestRlist ()); // 사용자의 권한 수집 info.AddStringPerMissions (user.getPerminsStrlist ()); 반품 정보; } // return null은 인터셉트 된 요청에 액세스 할 수 있도록합니다. }}4. 마지막으로 Ehcache의 구성 파일을 살펴보십시오.
<? xml version = "1.0"encoding = "utf-8"?> <ehcache xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance"xsi : nonamespaceschemalocation = "http://ehcache.org/ehcache <diskstore path = "java.io.tmpdir /tmp_ehcache" /> <!- 이름 : 캐시 이름. MaxelementsInmemory : 최대 캐시 수 MaxelementsOndisk : 하드 디스크의 최대 캐시 수. Eternal : 객체가 영구적으로 유효한지 여부를 설정하면 시간 초과가 작동하지 않습니다. 오버 플로우 토 디스크 : 디스크에 저장할지 여부, Timetoidleseconds : 객체가 만료되기 전에 허용되는 유휴 시간 (단위 : 초)을 설정합니다. Eternal = False 객체가 영구적으로 유효하지 않은 경우에만 사용되며 기본값은 0이므로 유휴 시간이 무한대입니다. Timetoliveseconds : 만료되기 전에 물체의 시간 (단위 : 초)을 설정합니다. 최대 시간은 생성 시간과 고장 시간 사이입니다. Eternal = False 객체가 영구적으로 유효하지 않은 경우에만 사용되며 기본값은 0입니다. 이는 물체의 생존 시간이 무한하다는 것을 의미합니다. DiskPersistent : 디스크 스토어가 가상 시스템의 재시작 사이에 지속되는지 여부. 기본값은 False입니다. Diskspoolbuffersizemb :이 매개 변수는 디스크 스토어 (디스크 캐시)의 캐시 크기를 설정합니다. 기본값은 30MB입니다. 각 캐시에는 자체 버퍼가 있어야합니다. diskexpirythreadintervalseconds : 디스크 고장 스레드 실행 시간 간격, 기본값은 120 초입니다. MemoryStoreEvictionPolicy : MaxelementsInMemory 한계에 도달하면 EHCache가 지정된 정책에 따라 메모리를 정리합니다. 기본 정책은 LRU (가장 최근에 사용)입니다. FIFO (우선, 우선) 또는 LFU (사용이 적음)로 설정할 수 있습니다. ClearOnflush : 메모리의 양이 최대의시기를 지울지 여부. MemoryStoreEvictionPolicy : Ehcache에 대한 세 가지 청소 전략; FIFO, 첫 번째로, 이것은 첫 번째 모든 사람에게 가장 친숙합니다. 덜 자주 사용되는 LFU는 위의 예에서 사용되는 전략입니다. 무딘이 되려면, 그것이 가장 많이 사용되지 않았다고 말하는 것입니다. 위에서 언급했듯이 캐시 된 요소는 적중 속성을 가지며 가장 낮은 적중 값이 캐시에서 지워집니다. LRU (최근에 사용 된 LRU) 캐시 된 요소에는 타임 스탬프가 있습니다. 캐시 용량이 가득 차서 새 요소를 캐시 할 공간을 만들어야하면 기존 캐시 요소에서 가장 먼 시간을 가진 요소가 캐시에서 지워집니다. -> <defaultCache Eternal = "False"MaxelementsInMemory = "1000"OverFlowTodisk = "False"DiskPersistent = "False"TimetoidleSeconds = "0"Timetoliveseconds = "600"MemoryStoreEvictionPolicy = "lru" /> <!-Login Record Cache Lock Login Login Record Cache Lock-<Cache FretryCache " Maxentrieslocalheap = "2000"Eternal = "False"Timetoidleseconds = "3600"Timetoliveseconds = "0"OverFlowTodisk = "false"통계 = "true"> </cache> </ehcache>
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.