spring boot 1.5.4 shiro+casを統合し、シングルポイント登録と権限制御を実現する。


1.maven依存を追加します。(まずcas-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-GUheN 64 mOZec 9 IWZSH 1 B-cas 01.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に统合して、単点登录と権限のコントロールを実现して、皆さんのために役に立つことを望んでいます。ここでも私たちのサイトを応援してくれてありがとうございます。