【 Shiro 】 Shiro 의 MVC, SpringBoot 통합 설정 및 상용 설정

79975 단어 분포 식
Shiro 설정
Shiro 의존 라 이브 러 리 가 져 오기
	<dependency>
		<groupId>org.apache.shirogroupId>
		<artifactId>shiro‐coreartifactId>
		<version>1.4.1version>
	dependency>
	
	<dependency>
		<groupId>org.apache.shirogroupId>
		<artifactId>shiro‐webartifactId>
		<version>1.4.1version>
	dependency>

	<dependency>
		<groupId>org.apache.shirogroupId>
		<artifactId>shiro‐springartifactId>
		<version>1.4.1version>
	dependency>

본 블 로그 설정 은 1.4.1 버 전 을 참고 로 하고 다른 버 전이 차이 가 있 으 면 공식 설정 을 위주 로 하 는 공식 설정 주 소 는 이 블 로그 밑 에 있 습 니 다.
SpringMVC 통합 Shiro
  • 모든 요청 차단
  • 
    <web‐app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema‐instance"
    	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
    	http://xmlns.jcp.org/xml/ns/javaee/web‐app_3_1.xsd"
    	version="3.1">
    	<context‐param>
    		<param‐name>contextConfigLocationparam‐name>
    		<param‐value>classpath:spring‐*.xmlparam‐value>
    	context‐param>
    	<listener>
    		<listener‐class>org.springframework.web.context.ContextLoaderListenerlistener‐class>
    	listener>
    	<servlet>
    		<servlet‐name>springMVCservlet‐name>
    		<servlet‐class>org.springframework.web.servlet.DispatcherServletservlet‐
    	class>
    		<init‐param>
    			<param‐name>contextConfigLocationparam‐name>
    			<param‐value>classpath:spring‐context*.xmlparam‐value>
    		init‐param>
    	servlet>
    	<servlet‐mapping>
    		<servlet‐name>springMVCservlet‐name>
    		<url‐pattern>*.dourl‐pattern>
    	servlet‐mapping>
    	<filter>
    		<filter‐name>shiroFilterfilter‐name>
    		<filter‐class>org.springframework.web.filter.DelegatingFilterProxyfilter‐class>
    		<init‐param>
    			<param‐name>targetFilterLifecycleparam‐name>
    			<param‐value>trueparam‐value>
    		init‐param>
    	filter>
    	<filter‐mapping>
    		<filter‐name>shiroFilterfilter‐name>
    		<url‐pattern>/*url‐pattern>
    	filter‐mapping>
    web‐app>
    

    spring - context - shiro. xml 설정 shiro 만 들 기
    
    <beans xmlns="http://www.springframework.org/schema/beans"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema‐instance"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans
    	http://www.springframework.org/schema/beans/spring‐beans.xsd">
    <!‐‐shiro   ‐‐>
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    	<property name="securityManager" ref="securityManager">property>
    	
    	<property name="loginUrl" value="/login.jsp">property>
    	
    	<!‐‐                          LoginController     ‐‐>
    	<property name="successUrl" value="/index.jsp">property>
    	<property name="unauthorizedUrl" value="/">property>
    	<property name="filterChainDefinitions">
    		<value>/**=anonvalue>
    	property>
    bean>
    
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor">bean>
    
    <!‐‐     ‐‐>
    <bean id="credentialsMatcher"
    class="org.apache.shiro.authc.credential.Md5CredentialsMatcher">bean>
    
    <!‐‐     Realm‐‐>
    <bean id="jdbcRealm" class="org.apache.shiro.realm.jdbc.JdbcRealm">
    	<property name="credentialsMatcher" ref="credentialsMatcher">property>
    	<property name="permissionsLookupEnabled" value="true">property>
    	<property name="dataSource" ref="dataSource">property>
    bean>
    
    <!‐‐    ‐‐>
    	<bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager">bean>
    	
    	<!‐‐shiro     ‐‐>
    	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    		<property name="realm" ref="jdbcRealm">property>
    		<property name="cacheManager" ref="cacheManager">property>
    	bean>
    beans>
    

    주 해 를 사용 하려 면 권한 검증 사용 주 해 를 설정 해 야 합 니 다.
    <!‐‐          ‐‐>
    <aop:config proxy‐target‐class="true">aop:config>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    	<property name="securityManager" ref="securityManager">property>
    bean>
    

    SpringBoot 응용 통합 Shiro 설정
  • SpringBoot 는 기본적으로 Shiro 에 대한 자동 설정 을 제공 하지 않 았 습 니 다
  • 자바 설정 방식
    @Configuration
    public class ShiroConfig {
    
       @Bean
        public ShiroDialect getShiroDialect(){
            return new ShiroDialect();
        }
        
        //   Realm
        @Bean
        public MyRealm getMyRealm(){
            MyRealm myRealm = new MyRealm();
            return myRealm;
        }
    
        @Bean
        public DefaultWebSecurityManager getDefaultWebSecurityManager(MyRealm myRealm){
            DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
            //securityManager     ,  realm
            securityManager.setRealm(myRealm);
            return securityManager;
        }
    
        @Bean
        public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager){
            ShiroFilterFactoryBean filter = new ShiroFilterFactoryBean();
            //     shiro         ,          SecurityManager 
            filter.setSecurityManager(securityManager);
            //      
            filter.setLoginUrl("/user/login");
    
            //  shiro     
            // anon          
            // authc         
            // user     RemeberMe      
            // perms         
            // role           
            Map<String,String> filterMap = new HashMap<>();
            filterMap.put("/","anon");
            filterMap.put("/login.html","anon");
            filterMap.put("/regist.html","anon");
            filterMap.put("/user/login","anon");
            filterMap.put("/user/regist","anon");
            filterMap.put("/static/**","anon");
            filterMap.put("/**","authc");
    
            filter.setFilterChainDefinitionMap(filterMap);
            filter.setLoginUrl("/login.html");
            //            
            filter.setUnauthorizedUrl("/login.html");
            return filter;
        }
    
    
    }
    
  • 사용자 정의 Realm
  • /**
     * 1.       AuthorizingRealm (   Realm    )
     * 2.  doGetAuthorizationInfo doGetAuthenticationInfo  
     * 3.  getName      realm        
     */
    public class MyRealm extends AuthorizingRealm {
        
        @Resource
        private UserDAO userDAO;
        @Resource
        private RoleDAO roleDAO;
        @Resource
        private PermissionDAO permissionDAO;
    
        public String getName() {
            return "myRealm";
        }
        
        /**
         *       (                 )
         */
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
            //        
            String username = (String) principalCollection.iterator().next();
            //                
            Set<String> roleNames = roleDAO.queryRoleNamesByUsername(username);
            //                
            Set<String> ps = permissionDAO.queryPermissionsByUsername(username);
    
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.setRoles(roleNames);
            info.setStringPermissions(ps);
            return info;
        }
    
        /**
         *          (              )
         */
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
            //  authenticationToken       subject.login(token)
            //  token      
            UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
            String username = token.getUsername();
            //     ,               
            User user = userDAO.queryUserByUsername(username);
    
            AuthenticationInfo info = new SimpleAuthenticationInfo(
                    username,           //       
                    user.getUserPwd(),   //             
                    getName());
    
            return info;
        }
    }
    

    Shiro 암호 화 인증 사용
    @Configuration
    public class ShiroConfig {
    
        //...
        @Bean
        public HashedCredentialsMatcher getHashedCredentialsMatcher(){
            HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
            //matcher          (        )
            matcher.setHashAlgorithmName("md5");
            //hash  
            matcher.setHashIterations(1);	//                      
            return matcher;
        }
    
        //   Realm
        @Bean
        public MyRealm getMyRealm( HashedCredentialsMatcher matcher ){
            MyRealm myRealm = new MyRealm();
            myRealm.setCredentialsMatcher(matcher);
            return myRealm;
        }
    
    	//...
    }
    
    

    캐 시 사용
    가 져 오기 의존
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-cacheartifactId>
    dependency>
    
    <dependency>
        <groupId>net.sf.ehcachegroupId>
        <artifactId>ehcacheartifactId>
    dependency>
    
    <dependency>
        <groupId>org.apache.shirogroupId>
        <artifactId>shiro-ehcacheartifactId>
        <version>1.4.0version>
    dependency>
    
  • 캐 시 정책 을 설정 하여 resources 디 렉 터 리 에 xml 파일 (ehcache. xml)
  • 을 만 듭 니 다.
    
    <ehcache updateCheck="false" dynamicConfig="false">
    
        <diskStore path="C:\TEMP" />
    
        <cache name="users"  timeToLiveSeconds="300"  maxEntriesLocalHeap="1000"/>
    
        <defaultCache name="defaultCache"
                      maxElementsInMemory="10000"
                      eternal="false"
                      timeToIdleSeconds="120"
                      timeToLiveSeconds="120"
                      overflowToDisk="false"
                      maxElementsOnDisk="100000"
                      diskPersistent="false"
                      diskExpiryThreadIntervalSeconds="120"
                      memoryStoreEvictionPolicy="LRU"/>
                
    ehcache>
    

    캐 시 관리 추가 (자바 설정)
    @Bean
    public EhCacheManager getEhCacheManager(){
       EhCacheManager ehCacheManager = new EhCacheManager();
       ehCacheManager.setCacheManagerConfigFile("classpath:ehcache.xml");
       return ehCacheManager;
    }
    
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(MyRealm myRealm){
       DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
       securityManager.setRealm(myRealm);
       securityManager.setCacheManager(getEhCacheManager());
       return securityManager;
    }
    

    세 션 관리
  • 사용자 정의 SessionManager: ShiroConfig. java
  • 설정
    @Bean
    public DefaultWebSessionManager getDefaultWebSessionManager(){
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        System.out.println("----------"+sessionManager.getGlobalSessionTimeout()); // 1800000
        //  sessionManager
        sessionManager.setGlobalSessionTimeout(5*60*1000);
        return sessionManager;
    }
    
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(MyRealm myRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myRealm);
        securityManager.setCacheManager(getEhCacheManager());
        securityManager.setSessionManager(getDefaultWebSessionManager());
        return securityManager;
    }
    

    기억 해 줘.
    필터 에 접근 할 수 있 는 url 을 설정 합 니 다.
    // anon              url
    // user              url(        )
    //authc              url
    //perms		               
    //logout	       url
    filterMap.put("/","anon");
    filterMap.put("/index.html","user");
    filterMap.put("/login.html","anon");
    filterMap.put("/regist.html","anon");
    filterMap.put("/user/login","anon");
    filterMap.put("/user/regist","anon");
    filterMap.put("/layui/**","anon");
    filterMap.put("/**","authc");
    filterMap.put("/c_add.html","perms[sys:c:save]");
    filterMap.put("/exit","logout");
    

    ShiroConfig. java 에 쿠키 기반 remembeMe 관리 자 를 설정 합 니 다.
    @Bean
    public CookieRememberMeManager cookieRememberMeManager(){
        CookieRememberMeManager rememberMeManager = new CookieRememberMeManager();
       
        //cookie    name
        SimpleCookie cookie = new SimpleCookie("rememberMe");
        cookie.setMaxAge(30*24*60*60);
        
        rememberMeManager.setCookie(cookie);
        return  rememberMeManager;
    }
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(MyRealm myRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myRealm);
        securityManager.setCacheManager(getEhCacheManager());
        securityManager.setSessionManager(getDefaultWebSessionManager());
        //  remember   
        securityManager.setRememberMeManager(cookieRememberMeManager());
        return securityManager;
    }
    

    로그 인 인증 시 token "기억 해 줘" 설정
  • 로그 인 페이지
  • <form action="/user/login" method="post">
        <p>  :<input type="text" name="userName"/>p>
        <p>  :<input type="text" name="userPwd"/>p>
        <p>   :<input type="checkbox" name="rememberMe"/>p>
        <p><input type="submit" value="  "/>p>
    form>
    

    컨트롤 러
    @Controller
    @RequestMapping("user")
    public class UserController {
    
        @Resource
        private UserServiceImpl userService;
    
        @RequestMapping("login")
        public String login(String userName,String userPwd,boolean rememberMe){
            try {
                userService.checkLogin(userName,userPwd,rememberMe);
                System.out.println("------    !");
                return "index";
            } catch (Exception e) {
                System.out.println("------    !");
                return "login";
            }
        }
    }
    

    service
    @Service
    public class UserServiceImpl {
    
        public void checkLogin(String userName, String userPwd,boolean rememberMe) throws Exception {
            //Shiro     ——  
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(userName,userPwd);
            token.setRememberMe(rememberMe);
            subject.login(token);
        }
    }
    

    참고 자료 Shiro 공식 설정:http://shiro.apache.org/spring.html.

    좋은 웹페이지 즐겨찾기