보안은 어디에나 있습니다. 나는 휴가를 이용하여 Shiro의 문서를 읽고 Shiro의 Spring Boot 통합을 문서화하여 데이터베이스의 역할에 따라 액세스 권한을 제어했습니다.
소개
Apache Shiro는 강력하고 유연한 오픈 소스 보안 프레임 워크입니다. 인증, 승인, 엔터프라이즈 세션 관리 및 암호화를 깨끗하게 처리합니다.
위의 그림은 시로의 기본 아키텍처를 보여줍니다
입증
때때로 사용자가 사용자 자체임을 증명하기 위해 "로그인"이라고합니다.
권한 부여
액세스 제어 프로세스, 즉 "누가"액세스 "를 결정합니다.
세션 관리
사용자 별 세션을 관리합니다. Shiro에서는 모든 사용자 세션 정보가 Shiro에 의해 제어되는 것을 알 수 있습니다.
암호화 (암호화)
데이터 소스에 대한 암호화 알고리즘으로 사용 편의성을 보장합니다.
시작
환경
Spring Boot 1.5.9 MySQL 5.7 Maven 3.5.2 Spring Data JPA Lombok
종속성을 추가하십시오
메인 시로 의존성 만 여기에 제공됩니다
<pectionency> <groupid> org.apache.shiro </groupid> <artifactid> Shiro-spring-boot-starter </artifactid> <버전> 1.4.0-rc2 </version> </dependency>
구성
당분간 사용자 테이블과 역할 테이블 만 있으면됩니다. Spring Boot에서 구성 파일을 수정하면 자동으로 데이터베이스 테이블이 생성됩니다.
서버 : 8888spring : dataSource : driver-class-name : com.mysql.jdbc.driver 사용자 이름 : 루트 비밀번호 : 루트 URL : jdbc : mysql : // localhost : 3306/shiro? char
실재
역할. 자바
@data @EntityPublic 클래스 역할 {@id @generatedValue 개인 정수 ID; 개인 긴 userID; 개인 문자열 역할;}user.java
@data @entitypublic class user {@id @generatedvalue private long id; 개인 문자열 사용자 이름; 개인 문자열 비밀번호;}왕국
먼저, Realm 클래스를 만들고, Realm을 승인하지 않고 상속 받고, 우리 자신의 권한 부여 및 인증 방법을 사용자 정의하십시오. Realm은 사용자, 역할 및 권한과 같은 응용 프로그램과 관련된 보안 데이터에 액세스 할 수있는 구성 요소입니다.
Realm.java
공개 클래스 영역은 REALM {@autowired private userservice userervice; // @override Protected AuthorizationInfo DogetAuthorizationInfo (PrincipalCollection PrincipalCollection) {// 자격 증명에서 사용자 이름 가져 오기 문자열 username = (String) sectods.getSubject (). getPrincipal (); // 사용자 이름을 기반으로 Query 사용자 객체 user = usererVice.getUserByUserName (username); // 사용자 목록에서 소유 한 역할 쿼리 <brole> list = roleservice.findbyUserId (user.getId ()); SimpleAuthorizationInfo info = New SimpleAuthorizationInfo (); for (역할 역할 : list) {// 사용자 역할 info.AddStringPermission (role.getRole ()); } 리턴 정보; } // @override Protected AuthenticationInfo DogetAuthenticationInfo (AuthenticationToken AuthenticationToken)가 AuthenticationException {// 현재 사용자 문자열의 사용자 이름을 얻습니다. // 데이터베이스에서 사용자 찾기 사용자 user = usererVice.getUserByUserName (username); if (userService.getUserByUserName (username) == null) {새로운 미지의 Accountexception ( "이 시스템에서 해당 사용자 정보가 발견되지 않았습니다."); } simpleAuthenticationInfo info = new SimpleAuthenticationInfo (user.getUername (), user.getPassword (), getName ()); 반품 정보; }}시로 구성 클래스
Shiroconfig.java
@ConfigurationPublic 클래스 ShiroConfig {@bean public shirofilterfactorybean shirofilterfactorybean (SecurityManager SecurityManager) {shirofilterfactorybean shirofilterfactorybean = new shirofilterfactoryBean (); shirofilterFactoryBean.SetSecurityManager (SecurityManager); Map <String, String> FilterChainDefinitionMap = New LinkedHashMap <String, String> (); // 다음은 필터 체인, 순서대로 필터링이므로/** 마지막 정적 자원을 넣어야합니다. // filterChainDefinitionMap.put ( "/favicon.ico", "anon"); // 웹 아이콘 FilterChainDefinitionMap.put ( "/**", "authc"); shirofilterFactoryBean.SetFilterChainDefinitionMap (FilterChainDefinitionMap); 반환 shirofilterfactorybean; } @bean public defaultwebsecurityManager SecurityManager () {defaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager (myRealm ()); 반환 기본websecurityManager; } @Bean Public MyRealm MyRealm () {MyRealm MyRealm = New MyRealm (); MyRealm을 반환합니다. }}제어 장치
Usercontroller.java
@ControllerPublic Class USERCONTROLLER {@autowired private userervice userervice; @getMapping ( "/") public String index () {return "index"; } @getMapping ( "/login") public String tologin () {return "login"; } @getMapping ( "/admin") public String admin () {return "admin"; } @postmapping ( "/login") public String dologin (문자열 사용자 이름, 문자열 암호) {usernamepasswordtoken token = new usernamepasswordToken (username, password); 대상 주제 = securityUtils.getSubject (); try {giversity.login (토큰); } catch (예외 e) {e.printstacktrace (); } "리디렉션 : admin"을 반환합니다. } @getMapping ( "/home") public string home () {주제 주제 = securityUtils.getSubject (); try {giversity.checkpermission ( "admin"); } catch (무단 exception Exception) {System.out.println ( "충분한 권한 없음"); } "집"리턴; } @getMapping ( "/logout") public String logout () {return "index"; }}서비스
Userservice.java
@ServicePublic Class UserserVice {@autowired private userDao userDao; 공개 사용자 getUserByUserName (String username) {return userDao.FindByUserName (username); } @RequiresRoles ( "admin") public void send () {System.out.println ( "이제 역할 관리자가 있고이 문을 실행할 수 있습니다"); }}디스플레이 레이어
admin.html
<! docType html> <html xmlns : th = "http://www.thymeleaf.org"> <html lang = "en"/> <head> <meta charset = "utf-8"/<titf-8 "/<titl> title> title </title> </head> <coad action ="/login "방법 ="<input type = "" "". 이름 = "사용자 이름" /> <입력 유형 = "비밀번호"이름 = "비밀번호" /> <입력 유형 = "제출"value = "로그인" /> < /form> < /body> < /html>
home.html
<! doctype html> <html xmlns : th = "http://www.thymeleaf.org"> <html lang = "en"/> <head> <meta charset = "title> title </title> </head> </body> home </html>
index.html
<! doctype html> <html xmlns : th = "http://www.thymeleaf.org"> <html lang = "en"/> <head> <meta charset = "utf-8"/> <utf-8 "/> <utf-8"/> <title> title </title> </head> </head> index <a href = "/login" "rel ="rel = " </a> </body> </html>
로그인 .html
<! docType html> <html xmlns : th = "http://www.thymeleaf.org"> <html lang = "en"/> <head> <meta charset = "utf-8"/<titf-8 "/<titl> title> title </title> </head> <coad action ="/login "방법 ="<input type = "" "". 이름 = "사용자 이름" /> <입력 유형 = "비밀번호"이름 = "비밀번호" /> <입력 유형 = "제출"value = "로그인" /> < /form> < /body> < /html>
요약
이 작은 사례는 역할에 따라 사용자 액세스의 제어를 구현하며, 그 중 가장 중요한 것은 영역이며 Shiro와 응용 프로그램 보안 데이터 사이의 "브리지"또는 "커넥터"역할을합니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.