spring boot 1.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 publicclassApplication{ /** *mainfunction *@paramargsparams */ publicstaticvoidmain(String[]args){ ConfigurableApplicationContextcontext=SpringApplication.run(Application.class,args); //testifaxmlbeaninjectintospringcontextsuccessful Useruser=(User)context.getBean("user1"); System.out.println(JSONObject.toJSONString(user)); } }
3.配置shiro+cas
packagecom.hdwang.config.shiroCas; importcom.hdwang.dao.UserDao; importorg.apache.shiro.cache.ehcache.EhCacheManager; importorg.apache.shiro.cas.CasFilter; importorg.apache.shiro.cas.CasSubjectFactory; importorg.apache.shiro.spring.LifecycleBeanPostProcessor; importorg.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; importorg.apache.shiro.spring.web.ShiroFilterFactoryBean; importorg.apache.shiro.web.filter.authc.LogoutFilter; importorg.apache.shiro.web.mgt.DefaultWebSecurityManager; importorg.jasig.cas.client.session.SingleSignOutFilter; importorg.jasig.cas.client.session.SingleSignOutHttpSessionListener; importorg.slf4j.Logger; importorg.slf4j.LoggerFactory; importorg.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; importorg.springframework.beans.factory.annotation.Qualifier; importorg.springframework.boot.web.servlet.FilterRegistrationBean; importorg.springframework.boot.web.servlet.ServletListenerRegistrationBean; importorg.springframework.context.annotation.Bean; importorg.springframework.context.annotation.Configuration; importorg.springframework.core.Ordered; importorg.springframework.web.filter.DelegatingFilterProxy; importjavax.servlet.Filter; importjavax.servlet.annotation.WebListener; importjava.util.HashMap; importjava.util.LinkedHashMap; importjava.util.Map; /** *Createdbyhdwangon2017/6/20. *shiro+cas配置 */ @Configuration publicclassShiroCasConfiguration{ privatestaticfinalLoggerlogger=LoggerFactory.getLogger(ShiroCasConfiguration.class); //casserver地址 publicstaticfinalStringcasServerUrlPrefix="https://localhost:8443/cas"; //Cas登录页面地址 publicstaticfinalStringcasLoginUrl=casServerUrlPrefix+"/login"; //Cas登出页面地址 publicstaticfinalStringcasLogoutUrl=casServerUrlPrefix+"/logout"; //当前工程对外提供的服务地址 publicstaticfinalStringshiroServerUrlPrefix="http://localhost:8081"; //casFilterUrlPattern publicstaticfinalStringcasFilterUrlPattern="/cas"; //登录地址 publicstaticfinalStringloginUrl=casLoginUrl+"?service="+shiroServerUrlPrefix+casFilterUrlPattern; //登出地址 publicstaticfinalStringlogoutUrl=casLogoutUrl+"?service="+shiroServerUrlPrefix; //登录成功地址 publicstaticfinalStringloginSuccessUrl="/home"; //权限认证失败跳转地址 publicstaticfinalStringunauthorizedUrl="/error/403.html"; @Bean publicEhCacheManagergetEhCacheManager(){ EhCacheManagerem=newEhCacheManager(); em.setCacheManagerConfigFile("classpath:ehcache-shiro.xml"); returnem; } @Bean(name="myShiroCasRealm") publicMyShiroCasRealmmyShiroCasRealm(EhCacheManagercacheManager){ MyShiroCasRealmrealm=newMyShiroCasRealm(); realm.setCacheManager(cacheManager); //realm.setCasServerUrlPrefix(ShiroCasConfiguration.casServerUrlPrefix); //客户端回调地址 //realm.setCasService(ShiroCasConfiguration.shiroServerUrlPrefix+ShiroCasConfiguration.casFilterUrlPattern); returnrealm; } /** *注册单点登出listener *@return */ @Bean publicServletListenerRegistrationBeansingleSignOutHttpSessionListener(){ ServletListenerRegistrationBeanbean=newServletListenerRegistrationBean(); bean.setListener(newSingleSignOutHttpSessionListener()); //bean.setName("");//默认为beanname bean.setEnabled(true); //bean.setOrder(Ordered.HIGHEST_PRECEDENCE);//设置优先级 returnbean; } /** *注册单点登出filter *@return */ @Bean publicFilterRegistrationBeansingleSignOutFilter(){ FilterRegistrationBeanbean=newFilterRegistrationBean(); bean.setName("singleSignOutFilter"); bean.setFilter(newSingleSignOutFilter()); bean.addUrlPatterns("/*"); bean.setEnabled(true); //bean.setOrder(Ordered.HIGHEST_PRECEDENCE); returnbean; } /** *注册DelegatingFilterProxy(Shiro) * *@return *@authorSHANHY *@create2016年1月13日 */ @Bean publicFilterRegistrationBeandelegatingFilterProxy(){ FilterRegistrationBeanfilterRegistration=newFilterRegistrationBean(); filterRegistration.setFilter(newDelegatingFilterProxy("shiroFilter")); //该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 filterRegistration.addInitParameter("targetFilterLifecycle","true"); filterRegistration.setEnabled(true); filterRegistration.addUrlPatterns("/*"); returnfilterRegistration; } @Bean(name="lifecycleBeanPostProcessor") publicLifecycleBeanPostProcessorgetLifecycleBeanPostProcessor(){ returnnewLifecycleBeanPostProcessor(); } @Bean publicDefaultAdvisorAutoProxyCreatorgetDefaultAdvisorAutoProxyCreator(){ DefaultAdvisorAutoProxyCreatordaap=newDefaultAdvisorAutoProxyCreator(); daap.setProxyTargetClass(true); returndaap; } @Bean(name="securityManager") publicDefaultWebSecurityManagergetDefaultWebSecurityManager(MyShiroCasRealmmyShiroCasRealm){ DefaultWebSecurityManagerdwsm=newDefaultWebSecurityManager(); dwsm.setRealm(myShiroCasRealm); // dwsm.setCacheManager(getEhCacheManager()); //指定SubjectFactory dwsm.setSubjectFactory(newCasSubjectFactory()); returndwsm; } @Bean publicAuthorizationAttributeSourceAdvisorgetAuthorizationAttributeSourceAdvisor(DefaultWebSecurityManagersecurityManager){ AuthorizationAttributeSourceAdvisoraasa=newAuthorizationAttributeSourceAdvisor(); aasa.setSecurityManager(securityManager); returnaasa; } /** *CAS过滤器 * *@return *@authorSHANHY *@create2016年1月17日 */ @Bean(name="casFilter") publicCasFiltergetCasFilter(){ CasFiltercasFilter=newCasFilter(); casFilter.setName("casFilter"); casFilter.setEnabled(true); //登录失败后跳转的URL,也就是Shiro执行CasRealm的doGetAuthenticationInfo方法向CasServer验证tiket casFilter.setFailureUrl(loginUrl);//我们选择认证失败后再打开登录页面 returncasFilter; } /** *ShiroFilter
*注意这里参数中的StudentService和IScoreDao只是一个例子,因为我们在这里可以用这样的方式获取到相关访问数据库的对象, *然后读取数据库相关配置,配置到shiroFilterFactoryBean的访问规则中。实际项目中,请使用自己的Service来处理业务逻辑。 * *@paramsecurityManager *@paramcasFilter *@paramuserDao *@return *@authorSHANHY *@create2016年1月14日 */ @Bean(name="shiroFilter") publicShiroFilterFactoryBeangetShiroFilterFactoryBean(DefaultWebSecurityManagersecurityManager,CasFiltercasFilter,UserDaouserDao){ ShiroFilterFactoryBeanshiroFilterFactoryBean=newShiroFilterFactoryBean(); //必须设置SecurityManager shiroFilterFactoryBean.setSecurityManager(securityManager); //如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面 shiroFilterFactoryBean.setLoginUrl(loginUrl); //登录成功后要跳转的连接 shiroFilterFactoryBean.setSuccessUrl(loginSuccessUrl); shiroFilterFactoryBean.setUnauthorizedUrl(unauthorizedUrl); //添加casFilter到shiroFilter中 Mapfilters=newHashMap<>(); filters.put("casFilter",casFilter); //filters.put("logout",logoutFilter()); shiroFilterFactoryBean.setFilters(filters); loadShiroFilterChain(shiroFilterFactoryBean,userDao); returnshiroFilterFactoryBean; } /** *加载shiroFilter权限控制规则(从数据库读取然后配置),角色/权限信息由MyShiroCasRealm对象提供doGetAuthorizationInfo实现获取来的 * *@authorSHANHY *@create2016年1月14日 */ privatevoidloadShiroFilterChain(ShiroFilterFactoryBeanshiroFilterFactoryBean,UserDaouserDao){ ///////////////////////下面这些规则配置最好配置到配置文件中/////////////////////// Map filterChainDefinitionMap=newLinkedHashMap (); //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请求采用logoutfilter //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); } }
packagecom.hdwang.config.shiroCas; importjavax.annotation.PostConstruct; importcom.hdwang.dao.UserDao; importcom.hdwang.entity.User; importorg.apache.shiro.SecurityUtils; importorg.apache.shiro.authc.AuthenticationInfo; importorg.apache.shiro.authc.AuthenticationToken; importorg.apache.shiro.authz.AuthorizationInfo; importorg.apache.shiro.authz.SimpleAuthorizationInfo; importorg.apache.shiro.cas.CasRealm; importorg.apache.shiro.subject.PrincipalCollection; importorg.slf4j.Logger; importorg.slf4j.LoggerFactory; importorg.springframework.beans.factory.annotation.Autowired; importjava.util.HashSet; importjava.util.Set; /** *Createdbyhdwangon2017/6/20. *安全数据源 */ publicclassMyShiroCasRealmextendsCasRealm{ privatestaticfinalLoggerlogger=LoggerFactory.getLogger(MyShiroCasRealm.class); @Autowired privateUserDaouserDao; @PostConstruct publicvoidinitProperty(){ //setDefaultRoles("ROLE_USER"); setCasServerUrlPrefix(ShiroCasConfiguration.casServerUrlPrefix); //客户端回调地址 setCasService(ShiroCasConfiguration.shiroServerUrlPrefix+ShiroCasConfiguration.casFilterUrlPattern); } ///** //*1、CAS认证,验证用户身份 //*2、将用户基本信息设置到会话中(不用了,随时可以获取的) //*/ //@Override //protectedAuthenticationInfodoGetAuthenticationInfo(AuthenticationTokentoken){ // //AuthenticationInfoauthc=super.doGetAuthenticationInfo(token); // //Stringaccount=(String)authc.getPrincipals().getPrimaryPrincipal(); // //Useruser=userDao.getByName(account); ////将用户信息存入session中 //SecurityUtils.getSubject().getSession().setAttribute("user",user); // //returnauthc; //} /** *权限认证,为当前登录的Subject授予角色和权限 *@see经测试:本例中该方法的调用时机为需授权资源被访问时 *@see经测试:并且每次访问需授权资源时都会执行该方法中的逻辑,这表明本例中默认并未启用AuthorizationCache *@see经测试:如果连续访问同一个URL(比如刷新),该方法不会被重复调用,Shiro有一个时间间隔(也就是cache时间,在ehcache-shiro.xml中配置),超过这个时间间隔再刷新页面,该方法会被执行 */ @Override protectedAuthorizationInfodoGetAuthorizationInfo(PrincipalCollectionprincipalCollection){ logger.info("##################执行Shiro权限认证##################"); //获取当前登录输入的用户名,等价于(String)principalCollection.fromRealm(getName()).iterator().next(); StringloginName=(String)super.getAvailablePrincipal(principalCollection); //到数据库查是否有此对象(1.本地查询2.可以远程查询casserver3.可以由casserver带过来角色/权限其它信息) Useruser=userDao.getByName(loginName);//实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法 if(user!=null){ //权限信息对象info,用来存放查出的用户的所有的角色(role)及权限(permission) SimpleAuthorizationInfoinfo=newSimpleAuthorizationInfo(); //给用户添加角色(让shiro去验证) SetroleNames=newHashSet<>(); 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]权限"); returninfo; } //返回null的话,就会导致任何用户访问被拦截的请求时,都会自动跳转到unauthorizedUrl指定的地址 returnnull; } }
packagecom.hdwang.controller; importcom.hdwang.config.shiroCas.ShiroCasConfiguration; importcom.hdwang.entity.User; importorg.springframework.stereotype.Controller; importorg.springframework.ui.Model; importorg.springframework.web.bind.annotation.RequestMapping; importorg.springframework.web.bind.annotation.RequestMethod; importjavax.servlet.http.HttpSession; /** *Createdbyhdwangon2017/6/21. *跳转至casserver去登录(一个入口) */ @Controller @RequestMapping("") publicclassCasLoginController{ /** *一般用不到 *@parammodel *@return */ @RequestMapping(value="/login",method=RequestMethod.GET) publicStringloginForm(Modelmodel){ model.addAttribute("user",newUser()); //return"login"; return"redirect:"+ShiroCasConfiguration.loginUrl; } @RequestMapping(value="logout",method={RequestMethod.GET, RequestMethod.POST}) publicStringloginout(HttpSessionsession) { return"redirect:"+ShiroCasConfiguration.logoutUrl; } }
packagecom.hdwang.controller; importcom.alibaba.fastjson.JSONObject; importcom.hdwang.entity.User; importcom.hdwang.service.datajpa.UserService; importorg.apache.shiro.SecurityUtils; importorg.apache.shiro.mgt.SecurityManager; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.stereotype.Controller; importorg.springframework.ui.ModelMap; importorg.springframework.web.bind.annotation.RequestMapping; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpSession; /** *Createdbyhdwangon2017/6/19. */ @Controller @RequestMapping("/home") publicclassHomeController{ @Autowired UserServiceuserService; @RequestMapping("") publicStringindex(HttpSessionsession,ModelMapmap,HttpServletRequestrequest){ //Useruser=(User)session.getAttribute("user"); System.out.println(request.getUserPrincipal().getName()); System.out.println(SecurityUtils.getSubject().getPrincipal()); UserloginUser=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/
casserver端登出(也行)
访问:https://localhost:8443/cas/logout
再访问:http://localhost:8081/home会跳转至登录页,perfect!
以上所述是小编给大家介绍的springboot1.5.4集成shiro+cas,实现单点登录和权限控制,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!