spring boot 1.5.4 통합 shiro+cas,단일 로그 인 및 권한 제어 실현

19988 단어 springbootshirocas
1.maven 의존 도 를 추가 합 니 다(케이스-server-3.5.2 를 먼저 설치 하고 설치 절 차 는 본 고의 참고 글 을 보십시오)

    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-spring</artifactId>
      <version>1.2.4</version>
    </dependency>
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-ehcache</artifactId>
      <version>1.2.4</version>
    </dependency>
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-cas</artifactId>
      <version>1.2.4</version>
    </dependency>    
2.누 적 된 추가@ServletComponentScan 주 해 를 시작 합 니 다.

@SpringBootApplication
public class Application {
  /**
   * main function
   * @param args params
   */
  public static void main(String[] args){
    ConfigurableApplicationContext context = SpringApplication.run(Application.class,args);
    //test if a xml bean inject into springcontext successful
    User user = (User)context.getBean("user1");
    System.out.println(JSONObject.toJSONString(user));
  }
}
 3.shiro+cas 설정

package com.hdwang.config.shiroCas;
import com.hdwang.dao.UserDao;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.cas.CasFilter;
import org.apache.shiro.cas.CasSubjectFactory;
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.filter.authc.LogoutFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.jasig.cas.client.session.SingleSignOutFilter;
import org.jasig.cas.client.session.SingleSignOutHttpSessionListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.filter.DelegatingFilterProxy;
import javax.servlet.Filter;
import javax.servlet.annotation.WebListener;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
 * Created by hdwang on 2017/6/20.
 * shiro+cas   
 */
@Configuration
public class ShiroCasConfiguration {
  private static final Logger logger = LoggerFactory.getLogger(ShiroCasConfiguration.class);
  // cas server  
  public static final String casServerUrlPrefix = "https://localhost:8443/cas";
  // Cas      
  public static final String casLoginUrl = casServerUrlPrefix + "/login";
  // Cas      
  public static final String casLogoutUrl = casServerUrlPrefix + "/logout";
  //              
  public static final String shiroServerUrlPrefix = "http://localhost:8081";
  // casFilter UrlPattern
  public static final String casFilterUrlPattern = "/cas";
  //     
  public static final String loginUrl = casLoginUrl + "?service=" + shiroServerUrlPrefix + casFilterUrlPattern;
  //     
  public static final String logoutUrl = casLogoutUrl+"?service="+shiroServerUrlPrefix;
  //       
  public static final String loginSuccessUrl = "/home";
  //           
  public static final String unauthorizedUrl = "/error/403.html";
  @Bean
  public EhCacheManager getEhCacheManager() {
    EhCacheManager em = new EhCacheManager();
    em.setCacheManagerConfigFile("classpath:ehcache-shiro.xml");
    return em;
  }
  @Bean(name = "myShiroCasRealm")
  public MyShiroCasRealm myShiroCasRealm(EhCacheManager cacheManager) {
    MyShiroCasRealm realm = new MyShiroCasRealm();
    realm.setCacheManager(cacheManager);
    //realm.setCasServerUrlPrefix(ShiroCasConfiguration.casServerUrlPrefix);
    //        
    //realm.setCasService(ShiroCasConfiguration.shiroServerUrlPrefix + ShiroCasConfiguration.casFilterUrlPattern);
    return realm;
  }
  /**
   *       listener
   * @return
   */
  @Bean
  public ServletListenerRegistrationBean singleSignOutHttpSessionListener(){
    ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean();
    bean.setListener(new SingleSignOutHttpSessionListener());
//    bean.setName(""); //   bean name
    bean.setEnabled(true);
    //bean.setOrder(Ordered.HIGHEST_PRECEDENCE); //     
    return bean;
  }
  /**
   *       filter
   * @return
   */
  @Bean
  public FilterRegistrationBean singleSignOutFilter(){
    FilterRegistrationBean bean = new FilterRegistrationBean();
    bean.setName("singleSignOutFilter");
    bean.setFilter(new SingleSignOutFilter());
    bean.addUrlPatterns("/*");
    bean.setEnabled(true);
    //bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
    return bean;
  }
  /**
   *   DelegatingFilterProxy(Shiro)
   *
   * @return
   * @author SHANHY
   * @create 2016 1 13 
   */
  @Bean
  public FilterRegistrationBean delegatingFilterProxy() {
    FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
    filterRegistration.setFilter(new DelegatingFilterProxy("shiroFilter"));
    //      false,       SpringApplicationContext  ,   true    ServletContainer  
    filterRegistration.addInitParameter("targetFilterLifecycle", "true");
    filterRegistration.setEnabled(true);
    filterRegistration.addUrlPatterns("/*");
    return filterRegistration;
  }
  @Bean(name = "lifecycleBeanPostProcessor")
  public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
    return new LifecycleBeanPostProcessor();
  }
  @Bean
  public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
    DefaultAdvisorAutoProxyCreator daap = new DefaultAdvisorAutoProxyCreator();
    daap.setProxyTargetClass(true);
    return daap;
  }
  @Bean(name = "securityManager")
  public DefaultWebSecurityManager getDefaultWebSecurityManager(MyShiroCasRealm myShiroCasRealm) {
    DefaultWebSecurityManager dwsm = new DefaultWebSecurityManager();
    dwsm.setRealm(myShiroCasRealm);
//   <!--     /    Cache,   EhCache    -->
    dwsm.setCacheManager(getEhCacheManager());
    //    SubjectFactory
    dwsm.setSubjectFactory(new CasSubjectFactory());
    return dwsm;
  }
  @Bean
  public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
    AuthorizationAttributeSourceAdvisor aasa = new AuthorizationAttributeSourceAdvisor();
    aasa.setSecurityManager(securityManager);
    return aasa;
  }
  /**
   * CAS   
   *
   * @return
   * @author SHANHY
   * @create 2016 1 17 
   */
  @Bean(name = "casFilter")
  public CasFilter getCasFilter() {
    CasFilter casFilter = new CasFilter();
    casFilter.setName("casFilter");
    casFilter.setEnabled(true);
    //         URL,    Shiro    CasRealm   doGetAuthenticationInfo    CasServer  tiket
    casFilter.setFailureUrl(loginUrl);//                 
    return casFilter;
  }
  /**
   * ShiroFilter<br/>
   *          StudentService   IScoreDao       ,                            ,
   *            ,    shiroFilterFactoryBean       。     ,      Service       。
   *
   * @param securityManager
   * @param casFilter
   * @param userDao
   * @return
   * @author SHANHY
   * @create 2016 1 14 
   */
  @Bean(name = "shiroFilter")
  public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager, CasFilter casFilter, UserDao userDao) {
    ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
    //      SecurityManager
    shiroFilterFactoryBean.setSecurityManager(securityManager);
    //             Web       "/login.jsp"  
    shiroFilterFactoryBean.setLoginUrl(loginUrl);
    //            
    shiroFilterFactoryBean.setSuccessUrl(loginSuccessUrl);
    shiroFilterFactoryBean.setUnauthorizedUrl(unauthorizedUrl);
    //   casFilter shiroFilter 
    Map<String, Filter> filters = new HashMap<>();
    filters.put("casFilter", casFilter);
    // filters.put("logout",logoutFilter());
    shiroFilterFactoryBean.setFilters(filters);
    loadShiroFilterChain(shiroFilterFactoryBean, userDao);
    return shiroFilterFactoryBean;
  }
  /**
   *   shiroFilter      (          ),  /     MyShiroCasRealm    doGetAuthorizationInfo      
   *
   * @author SHANHY
   * @create 2016 1 14 
   */
  private void loadShiroFilterChain(ShiroFilterFactoryBean shiroFilterFactoryBean, UserDao userDao){
    ///////////////////////                    ///////////////////////
    Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
    // authc:                 ,  Shiro        org.apache.shiro.web.filter.authc.FormAuthenticationFilter
    // anon:         
    // user:        
    // roles["admin"]     admin  
    // perms["permission1"]     permission1  
    // filter          ,      ,      。
    // url       :? * **,      1 ,  0-n (     ),        
    //1.shiro  cas ,       
    filterChainDefinitionMap.put(casFilterUrlPattern, "casFilter");
    //filterChainDefinitionMap.put("/logout","logout"); //logut    logout filter
    //2.      
    filterChainDefinitionMap.put("/css/**","anon");
    filterChainDefinitionMap.put("/js/**","anon");
    filterChainDefinitionMap.put("/login", "anon");
    filterChainDefinitionMap.put("/logout","anon");
    filterChainDefinitionMap.put("/error","anon");
    //3.     (           casserver  (webservice,http     ),            )
    filterChainDefinitionMap.put("/user", "authc"); //    
    filterChainDefinitionMap.put("/user/add/**", "authc,roles[admin]"); //    ,      admin
    filterChainDefinitionMap.put("/user/delete/**", "authc,perms[\"user:delete\"]"); //    ,       user:delete
    //4.       
    filterChainDefinitionMap.put("/**", "user");
    shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
  }
}

package com.hdwang.config.shiroCas;
import javax.annotation.PostConstruct;
import com.hdwang.dao.UserDao;
import com.hdwang.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cas.CasRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashSet;
import java.util.Set;
/**
 * Created by hdwang on 2017/6/20.
 *      
 */
public class MyShiroCasRealm extends CasRealm{
  private static final Logger logger = LoggerFactory.getLogger(MyShiroCasRealm.class);
  @Autowired
  private UserDao userDao;
  @PostConstruct
  public void initProperty(){
//   setDefaultRoles("ROLE_USER");
    setCasServerUrlPrefix(ShiroCasConfiguration.casServerUrlPrefix);
    //        
    setCasService(ShiroCasConfiguration.shiroServerUrlPrefix + ShiroCasConfiguration.casFilterUrlPattern);
  }
//  /**
//   * 1、CAS   ,      
//   * 2、             (   ,       )
//   */
//  @Override
//  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
//
//    AuthenticationInfo authc = super.doGetAuthenticationInfo(token);
//
//    String account = (String) authc.getPrincipals().getPrimaryPrincipal();
//
//    User user = userDao.getByName(account);
//    //       session 
//    SecurityUtils.getSubject().getSession().setAttribute("user", user);
//
//    return authc;
//  }
  /**
   *     ,      Subject       
   * @see    :                     
   * @see    :                       ,            AuthorizationCache
   * @see    :         URL(    ),          ,Shiro       (   cache  , ehcache-shiro.xml   ),             ,       
   */
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    logger.info("##################  Shiro    ##################");
    //            ,   (String) principalCollection.fromRealm(getName()).iterator().next();
    String loginName = (String)super.getAvailablePrincipal(principalCollection);
    //           (1.     2.      casserver 3.   casserver     /      )
    User user=userDao.getByName(loginName);//      ,             ,    ,Shiro           ,2            
    if(user!=null){
      //      info,               (role)   (permission)
      SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
      //       ( shiro   )
      Set<String> roleNames = new HashSet<>();
      if(user.getName().equals("boy5")){
        roleNames.add("admin");
      }
      info.setRoles(roleNames);
      if(user.getName().equals("  ")){
        //       ( shiro   )
        info.addStringPermission("user:delete");
      }
      //          
      //      ,          ,         admin  
//      simpleAuthorInfo.addRole("admin");
      //    
//      simpleAuthorInfo.addStringPermission("admin:manage");
//      logger.info("    [mike]   [admin]   [admin:manage]  ");
      return info;
    }
    //   null  ,                 ,       unauthorizedUrl     
    return null;
  }
}

package com.hdwang.controller;
import com.hdwang.config.shiroCas.ShiroCasConfiguration;
import com.hdwang.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpSession;
/**
 * Created by hdwang on 2017/6/21.
 *    cas server   (    )
 */
@Controller
@RequestMapping("")
public class CasLoginController {
  /**
   *      
   * @param model
   * @return
   */
  @RequestMapping(value="/login",method= RequestMethod.GET)
  public String loginForm(Model model){
    model.addAttribute("user", new User());
//   return "login";
    return "redirect:" + ShiroCasConfiguration.loginUrl;
  }
  @RequestMapping(value = "logout", method = { RequestMethod.GET,
      RequestMethod.POST })
  public String loginout(HttpSession session)
  {
    return "redirect:"+ShiroCasConfiguration.logoutUrl;
  }
}

package com.hdwang.controller;
import com.alibaba.fastjson.JSONObject;
import com.hdwang.entity.User;
import com.hdwang.service.datajpa.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
 * Created by hdwang on 2017/6/19.
 */
@Controller
@RequestMapping("/home")
public class HomeController {
  @Autowired
  UserService userService;
  @RequestMapping("")
  public String index(HttpSession session, ModelMap map, HttpServletRequest request){
//    User user = (User) session.getAttribute("user");
    System.out.println(request.getUserPrincipal().getName());
    System.out.println(SecurityUtils.getSubject().getPrincipal());
    User loginUser = userService.getLoginUser();
    System.out.println(JSONObject.toJSONString(loginUser));
    map.put("user",loginUser);
    return "home";
  }
}
 4.실행 검증
로그 인
방문:http://localhost:8081/home
다음으로 이동:https://localhost:8443/cas/login?service=http://localhost:8081/cas
올 바른 사용자 이름 비밀 번 호 를 입력 하고 로그 인 후 이동:http://localhost:8081/cas?ticket=ST-203-GUheN64mOZec9IWZSH1B-cas01.example.org
최종 점프:http://localhost:8081/home
게재 하 다
방문:http://localhost:8081/logout
다음으로 이동:https://localhost:8443/cas/logout?service=http://localhost:8081
로그 인 하지 않 았 고 로그 인 절 차 를 실행 하 였 기 때문에 최종 반환https://localhost:8443/cas/login?service=http://localhost:8081/cas
이번 접속 성공 후 돌아 오기:http://localhost:8081/
cas server 엔 드 로그 인(해도 됩 니 다)
방문:https://localhost:8443/cas/logout
재 방문:http://localhost:8081/home로그 인 페이지 로 이동 합 니 다.perfect!
위 에서 말 한 것 은 소 편 이 소개 한 spring boot 1.5.4 집성 shiro+cas 로 단일 로그 인 과 권한 통 제 를 실현 하 는 데 도움 이 되 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 메 시 지 를 남 겨 주세요.소 편 은 제때에 답 해 드 리 겠 습 니 다.여기 서도 저희 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!

좋은 웹페이지 즐겨찾기