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 {
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;
@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;
}
@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;
}
@Bean
public FilterRegistrationBean singleSignOutFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setName("singleSignOutFilter");
bean.setFilter(new SingleSignOutFilter());
bean.addUrlPatterns("
@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("
@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;
}
@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;
}
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匹配通配符支持:? * **,分别表示匹配1个,匹配0-n个(不含子路径),匹配下级所有路径
//1.shiro集成cas后,首先添加该规则
filterChainDefinitionMap.put(casFilterUrlPattern, "casFilter");
//filterChainDefinitionMap.put("/logout","logout"); //logut请求采用logout filter
//2.不拦截的请求
filterChainDefinitionMap.put("/css
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);
}
//
// @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;
// }
@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;
@Controller
@RequestMapping("")
public class CasLoginController {
@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;
@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,实现单点登录和权限控制,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对考高分网网站的支持!



