热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

springboot1.5.4集成shiro+cas,实现单点登录和权限控制

这篇文章主要介绍了springboot1.5.4集成shiro+cas,实现单点登录和权限控制,需要的朋友可以参考下

1.添加maven依赖(先安装好cas-server-3.5.2,安装步骤请查看本文参考文章)

    
      org.apache.shiro
      shiro-spring
      1.2.4
    
    
      org.apache.shiro
      shiro-ehcache
      1.2.4
    
    
      org.apache.shiro
      shiro-cas
      1.2.4
        

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);
//   
    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
* 注意这里参数中的 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 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 filterChainDefinitiOnMap= new LinkedHashMap(); // authc:该过滤器下的页面必须登录后才能访问,它是Shiro内置的一个拦截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter // anon: 可以理解为不拦截 // user: 登录了就不拦截 // roles["admin"] 用户拥有admin角色 // perms["permission1"] 用户拥有permission1权限 // filter顺序按照定义顺序匹配,匹配到就验证,验证完毕结束。 // url匹配通配符支持:&#63; * **,分别表示匹配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 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&#63;service=http://localhost:8081/cas

输入正确用户名密码登录跳转回:http://localhost:8081/cas&#63;ticket=ST-203-GUheN64mOZec9IWZSH1B-cas01.example.org

最终跳回:http://localhost:8081/home

登出

访问:http://localhost:8081/logout

跳转至:https://localhost:8443/cas/logout&#63;service=http://localhost:8081

由于未登录,又执行登录步骤,所以最终返回https://localhost:8443/cas/login&#63;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,实现单点登录和权限控制,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!


推荐阅读
  • VScode格式化文档换行或不换行的设置方法
    本文介绍了在VScode中设置格式化文档换行或不换行的方法,包括使用插件和修改settings.json文件的内容。详细步骤为:找到settings.json文件,将其中的代码替换为指定的代码。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 这是原文链接:sendingformdata许多情况下,我们使用表单发送数据到服务器。服务器处理数据并返回响应给用户。这看起来很简单,但是 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • Java验证码——kaptcha的使用配置及样式
    本文介绍了如何使用kaptcha库来实现Java验证码的配置和样式设置,包括pom.xml的依赖配置和web.xml中servlet的配置。 ... [详细]
  • 本文介绍了数据库的存储结构及其重要性,强调了关系数据库范例中将逻辑存储与物理存储分开的必要性。通过逻辑结构和物理结构的分离,可以实现对物理存储的重新组织和数据库的迁移,而应用程序不会察觉到任何更改。文章还展示了Oracle数据库的逻辑结构和物理结构,并介绍了表空间的概念和作用。 ... [详细]
  • CSS3选择器的使用方法详解,提高Web开发效率和精准度
    本文详细介绍了CSS3新增的选择器方法,包括属性选择器的使用。通过CSS3选择器,可以提高Web开发的效率和精准度,使得查找元素更加方便和快捷。同时,本文还对属性选择器的各种用法进行了详细解释,并给出了相应的代码示例。通过学习本文,读者可以更好地掌握CSS3选择器的使用方法,提升自己的Web开发能力。 ... [详细]
  • 生成对抗式网络GAN及其衍生CGAN、DCGAN、WGAN、LSGAN、BEGAN介绍
    一、GAN原理介绍学习GAN的第一篇论文当然由是IanGoodfellow于2014年发表的GenerativeAdversarialNetworks(论文下载链接arxiv:[h ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • t-io 2.0.0发布-法网天眼第一版的回顾和更新说明
    本文回顾了t-io 1.x版本的工程结构和性能数据,并介绍了t-io在码云上的成绩和用户反馈。同时,还提到了@openSeLi同学发布的t-io 30W长连接并发压力测试报告。最后,详细介绍了t-io 2.0.0版本的更新内容,包括更简洁的使用方式和内置的httpsession功能。 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
  • 使用在线工具jsonschema2pojo根据json生成java对象
    本文介绍了使用在线工具jsonschema2pojo根据json生成java对象的方法。通过该工具,用户只需将json字符串复制到输入框中,即可自动将其转换成java对象。该工具还能解析列表式的json数据,并将嵌套在内层的对象也解析出来。本文以请求github的api为例,展示了使用该工具的步骤和效果。 ... [详细]
  • ZSI.generate.Wsdl2PythonError: unsupported local simpleType restriction ... [详细]
  • 推荐系统遇上深度学习(十七)详解推荐系统中的常用评测指标
    原创:石晓文小小挖掘机2018-06-18笔者是一个痴迷于挖掘数据中的价值的学习人,希望在平日的工作学习中,挖掘数据的价值, ... [详细]
author-avatar
liu100897
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有