cas4.2.7与shiro进行整合

准备工作

  cas单点登录开始前准备,请参考cas4.2.7实现单点登录。

与shiro进行整合

  注:准备工作的基础上,对cas客户端进行如下改进。

  引入相关jar包

shiro-cas-1.2.6.jar
shiro-core-1.2.6.jar
shiro-spring-1.2.6.jar
shiro-web-1.2.6.jar

  web.xml引入shiro过滤器

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"><display-name>Archetype Created Web Application</display-name><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-web.xml, classpath:spring-shiro.xml</param-value></context-param><!-- Shiro配置 --><filter><filter-name>shiroFilter</filter-name><filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class><init-param><param-name>targetFilterLifecycle</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>shiroFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- ****************** 单点登录开始 ********************--><!-- 用于实现单点登出功能  可选 --><listener><listener-class>org.jasig.cas.client.session.SingleSignOutHttpSessionListener</listener-class></listener><!-- 该过滤器用于实现单点登出功能,单点退出配置,一定要放在其他filter之前 可选 --><filter><filter-name>CAS Single Sign Out Filter</filter-name><filter-class>org.jasig.cas.client.session.SingleSignOutFilter</filter-class><init-param><param-name>casServerUrlPrefix</param-name><param-value>http://127.0.0.1:8080/cas-web/</param-value></init-param></filter><filter-mapping><filter-name>CAS Single Sign Out Filter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- 该过滤器对HttpServletRequest请求包装, 可通过HttpServletRequest的getRemoteUser()方法获得登录用户的登录名,可选 --><filter><filter-name>CAS HttpServletRequest Wrapper Filter</filter-name><filter-class>org.jasig.cas.client.util.HttpServletRequestWrapperFilter</filter-class></filter><filter-mapping><filter-name>CAS HttpServletRequest Wrapper Filter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- 该过滤器使得可以通过org.jasig.cas.client.util.AssertionHolder来获取用户的登录名。比如AssertionHolder.getAssertion().getPrincipal().getName()。这个类把Assertion信息放在ThreadLocal变量中,这样应用程序不在web层也能够获取到当前登录信息 --><filter><filter-name>CAS Assertion Thread Local Filter</filter-name><filter-class>org.jasig.cas.client.util.AssertionThreadLocalFilter</filter-class></filter><filter-mapping><filter-name>CAS Assertion Thread Local Filter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- ****************** 单点登录结束 ********************--><servlet><servlet-name>springMVC</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-web.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>springMVC</servlet-name><url-pattern>/</url-pattern></servlet-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list>
</web-app>

  引入shiro的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><context:property-placeholder location="classpath:shiro.properties" ignore-unresolvable="true"/><bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"><property name="securityManager" ref="securityManager"/><!-- 设定角色的登录链接,这里为cas登录页面的链接可配置回调地址  --><property name="loginUrl" value="${cas.loginUrl}" /><property name="successUrl" value="${shiro.successUrl}" /><property name="filters"><map><entry key="casFilter" value-ref="casFilter"/></map></property><property name="filterChainDefinitions"><value>/shiro-cas = casFilter/** = authc</value></property></bean><bean id="casFilter" class="org.apache.shiro.cas.CasFilter"><property name="failureUrl" value="${shiro.failureUrl}"/></bean><bean id="ShiroCasRealm" class="com.hjzgg.client.shiro.ShiroCasRealm"/><bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"><property name="realm" ref="ShiroCasRealm"/><property name="subjectFactory" ref="casSubjectFactory"/></bean><bean id="casSubjectFactory" class="org.apache.shiro.cas.CasSubjectFactory"/><bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/><bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"><property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/><property name="arguments" ref="securityManager"/></bean>
</beans>

  引入shiro的需要属性

cas.loginUrl=http://127.0.0.1:8080/cas-web/login?service=http://127.0.0.1:8080/cas-client/shiro-cas
cas.logoutUrl=http://127.0.0.1:8080/cas-web/logout?service=http://127.0.0.1:8080/cas-client/shiro-cas
cas.serverUrlPrefix=http://127.0.0.1:8080/cas-web
shiro.cas.service=http://127.0.0.1:8080/cas-client/shiro-cas
shiro.failureUrl=/error
shiro.successUrl=/success

  自定义shiro的realm

package com.hjzgg.client.shiro;import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cas.CasAuthenticationException;
import org.apache.shiro.cas.CasToken;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.StringUtils;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.util.AssertionHolder;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.Cas20ServiceTicketValidator;
import org.jasig.cas.client.validation.TicketValidationException;
import org.jasig.cas.client.validation.TicketValidator;
import org.springframework.beans.factory.annotation.Value;import java.util.ArrayList;
import java.util.List;
import java.util.Map;public class ShiroCasRealm extends AuthorizingRealm {@Value("${shiro.cas.service}")private String shiroCasServiceUrl;@Value("${cas.serverUrlPrefix}")private String casServerUrlPrefix;@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {AttributePrincipal principal = AssertionHolder.getAssertion().getPrincipal();if (principal != null) {Map<String, Object> attributes = principal.getAttributes();if (attributes.size() > 0) {
//                List<String> roles = CommonUtils.arrayStringtoArrayList((String)attributes.get("roles"));List<String> roles = null;//权限信息对象info,用来存放查出的用户的所有的角色(role)及权限(permission)SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();//用户的角色集合      
                info.addRoles(roles);//用户的角色对应的所有权限,如果只使用角色定义访问权限,下面的一行可以不要      //info.addStringPermissions(user.getPermissionList());
            }}return null;}@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {CasToken casToken = (CasToken) token;if (token == null)return null;String ticket = (String) casToken.getCredentials();if (!StringUtils.hasText(ticket))return null; Cas20ServiceTicketValidator cas20ServiceTicketValidator = new Cas20ServiceTicketValidator(casServerUrlPrefix);cas20ServiceTicketValidator.setEncoding("utf-8");TicketValidator ticketValidator = cas20ServiceTicketValidator;try {Assertion casAssertion = ticketValidator.validate(ticket, shiroCasServiceUrl);AttributePrincipal casPrincipal = casAssertion.getPrincipal();String userId = casPrincipal.getName();List principals = new ArrayList<String>();if (casPrincipal != null) {Map<String, Object> attributes = casPrincipal.getAttributes();principals.add(userId);principals.add(attributes);}PrincipalCollection principalCollection = new SimplePrincipalCollection(principals, getName());return new SimpleAuthenticationInfo(principalCollection, ticket);} catch (TicketValidationException e) {throw new CasAuthenticationException((new StringBuilder()).append("Unable to validate ticket [").append(ticket).append("]").toString(), e);}}@Overrideprotected void onInit() {super.onInit();this.setAuthenticationTokenClass(CasToken.class);}
}

  引入日志系统

    http://www.cnblogs.com/hujunzheng/p/6926429.html

遇到的问题

  shiro+cas学习及整合问题

  cas4.2.7学习笔记

项目地址

  https://github.com/hjzgg/cas4.2.7-authentication/tree/shiro+cas

 

转载于:https://www.cnblogs.com/hujunzheng/p/6928498.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/531259.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

命令行fuck神器

文章 thefuck git thefuck 转载于:https://www.cnblogs.com/hujunzheng/p/6935587.html

springmvc配置MappingJackson2HttpMessageConverter实现属性驼峰和下划线的转换

需求 php调用java接口时&#xff0c;因为php那边的属性都是下划线风格&#xff0c;java这边的属性都是驼峰的风格。配置springmvc的json转换&#xff0c;在requestBody的时候&#xff08;调用对象的set 方法&#xff09;将java属性name映射成下划线形式 和 请求的参数匹配&…

springmvc中使用MockMvc测试controller

示例代码 import com.alibaba.fastjson.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springfra…

swagger restful api form映射实体对象和body映射实体对象配置

实体Model ModelAttribute一个具有如下三个作用&#xff1a; ①绑定请求参数到命令对象&#xff1a;放在功能处理方法的入参上时&#xff0c;用于将多个请求参数绑定到一个命令对象&#xff0c;从而简化绑定流程&#xff0c;而且自动暴露为模型数据用于视图页面展示时使用&…

程序员的开发文档

Web版&#xff1a; DevDocs API Documentation 桌面版&#xff1a;devdocs-app 转载于:https://www.cnblogs.com/hujunzheng/p/7015947.html

ssh端口转发(之kettle ssh方式连接数据库)

ssh参数解释 格式  ssh [user]host [command] 选项&#xff1a; -1&#xff1a;强制使用ssh协议版本1&#xff1b; -2&#xff1a;强制使用ssh协议版本2&#xff1b; -4&#xff1a;强制使用IPv4地址&#xff1b; -6&#xff1a;强制使用IPv6地址&#xff1b; -A&#xff1a…

ThreadLocal和InheritableThreadLocal使用

InheritableThreadLocal代码 public class InheritableThreadLocal<T> extends ThreadLocal<T> {protected T childValue(T parentValue) {return parentValue;}ThreadLocalMap getMap(Thread t) {return t.inheritableThreadLocals;}void createMap(Thread t, T f…

mybatis generator修改默认生成的sql模板

相关连接&#xff1a; mybatis-generator扩展教程系列 -- 自定义sql xml文件 git项目地址 转载于:https://www.cnblogs.com/hujunzheng/p/7110510.html

oauth简单使用

一、oauth原理参考 理解OAuth 2.0 二、本例中采用授权码模式 大致流程 &#xff08;A&#xff09;用户访问客户端&#xff0c;后者将前者导向认证服务器。  &#xff08;B&#xff09;用户选择是否给予客户端授权。  &#xff08;C&#xff09;假设用户给予授权&#xff0c…

我眼中的服务提供和服务消费

服务提供和消费脑图 服务提供和消费脑图 参见: 服务提供者, 服务消费者, 服务注册中心 服务提供者 1.服务提供者启动&#xff0c;解析xml文件中配置的服务&#xff0c;这里使用Dom4j解析。 2.将服务的一些相关信息注册到 服务注册中心。 注&#xff1a;服务相关信息&#xff1a…

shiro整合oauth

前言 如果oauth原理还不清楚的地方&#xff0c;其参考这里。 一、基本思路脑图 二、客户端shiro配置 shiro配置文件 <?xml version"1.0" encoding"UTF-8"?> <beans xmlns"http://www.springframework.org/schema/beans"xmlns:util&q…

springmvc+swagger2

一、swagger2依赖 <!--swagger--> <dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><exclusions><exclusion><artifactId>spring-aop</artifactId><groupId>org.s…

获取资源文件工具类

如果没有依赖spring&#xff0c;可以将分割线下的方法去掉 import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframe…

无状态shiro认证组件(禁用默认session)

准备内容 简单的shiro无状态认证 无状态认证拦截器 import com.hjzgg.stateless.shiroSimpleWeb.Constants; import com.hjzgg.stateless.shiroSimpleWeb.realm.StatelessToken; import org.apache.shiro.web.filter.AccessControlFilter;import javax.servlet.ServletRequest;…

Spring根据包名获取包路径下的所有类

参考mybatis MapperScannerConfigurer.java 最终找到 Spring的一个类 ClassPathBeanDefinitionScanner.java 参考ClassPathBeanDefinitionScanner 和它的父类 ClassPathScanningCandidateComponentProvider&#xff0c;将一些代码进行抽取&#xff0c;得到如下工具类。 import…

java8 Optional正确使用姿势

Java 8 如何正确使用 Optional import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import org.apache.commons.lang3.StringUtils;import java.util.Optional;Data EqualsAndHashCode(exclude{"self"}) ToString(callSupertrue, exclud…

idea springboot热部署无效问题

Intellij IDEA 使用Spring-boot-devTools无效解决办法 springboot项目中遇到的bug <dependencies><!--spring boot 热加载--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId&g…

lintcode 单词接龙II

题意 给出两个单词&#xff08;start和end&#xff09;和一个字典&#xff0c;找出所有从start到end的最短转换序列 比如&#xff1a; 1、每次只能改变一个字母。 2、变换过程中的中间单词必须在字典中出现。 注意事项 所有单词具有相同的长度。所有单词都只包含小写字母。样例…

lintcode 最大子数组III

题目描述 给定一个整数数组和一个整数 k&#xff0c;找出 k 个不重叠子数组使得它们的和最大。每个子数组的数字在数组中的位置应该是连续的。 返回最大的和。 注意事项 子数组最少包含一个数 样例 给出数组 [-1,4,-2,3,-2,3] 以及 k 2&#xff0c;返回 8 思路 dp[i][j] max(…

idea模板注释

类文件头部的注释 #if (${PACKAGE_NAME} && ${PACKAGE_NAME} ! "")package ${PACKAGE_NAME};#end #parse("File Header.java") /** * ${DESCRIPTION} * author ${USER} hujunzheng * create ${YEAR}-${MONTH}-${DAY} ${TIME} **/ public class ${N…