Shiro之CAS单点登录-yellowcong

来源:互联网 发布:eclipse更改端口号 编辑:程序博客网 时间:2024/05/17 02:50

配置单点登录,有点坑的是,我将Session存在了缓存中,导致我每次登录的时候,都不去cas验证中心,我就感觉很无语,后来将sessionManager删除后,就好用了,太坑了,这问题坑了一天多。实现Cas单点登录的步骤:1、添加shiro-cas的依赖包,2、继承Shiro-cas中的Realm,3、配置spring-shiro.xml,引用Realm和cas的过滤器到shiro中,4、配置shiro.properties,设置访问的cas服务器和客户端,5、配置spring.xml,添加shiro.properties到spring中,6、配置web.xml添加cas的登出过滤器

源码地址

https://gitee.com/yellowcong/shior-dmeo/tree/master/test_cas

学习准备

搭建Cas服务器

服务架构

节点 服务 http://127.0.0.1:8081/https://127.0.0.1:8843 cas服务器 http://127.0.0.1:8080 节点1

单点登录

1、客户端发请求到目标服务器
2、目标服务器发请求,重定向到cas服务器
3、用户输入用户名和密码后,cas服务器重定向到目标服务器,带回ticket
4、目标服务器根据ticket发送请求到cas服务,来获取到登录用户信息
5、cas服务返回验证消息给目标服务

这里写图片描述

目录结构

这里写图片描述

实现步骤

1、导入依赖包

<dependency>    <groupId>org.apache.shiro</groupId>    <artifactId>shiro-cas</artifactId>    <version>${shiro.version}</version></dependency>

2、添加自定义Reamle,需要实现CasRealm 。

package com.yellowcong.shiro.realm;import java.util.Set;import org.apache.shiro.SecurityUtils;import org.apache.shiro.authc.AuthenticationException;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.springframework.beans.factory.annotation.Autowired;import com.yellowcong.service.RolePermissionService;import com.yellowcong.service.UserRoleService;import com.yellowcong.service.UserService;import com.yellowcong.shiro.model.User;/** * 创建日期:2017/12/21<br/> * 创建时间:17:57:14<br/> * 创建用户:yellowcong<br/> * 机能概要:创建Cas的realm,需要继承CasRealm 类 */public class WebCasRealm extends CasRealm {    @Autowired    private UserService userService;    @Autowired    private UserRoleService userRoleService;    @Autowired    private RolePermissionService rolePermissionService;    @Override    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {        // 用户名称        Object username = principals.getPrimaryPrincipal();        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();        // 根据用户ID查询角色(role),放入到Authorization里。        Set<String> roles = userRoleService.getRoleByName(username.toString());        info.setRoles(roles);        // 根据用户ID查询权限(permission),放入到Authorization里。        Set<String> permissions = null;        if (roles.size() > 0) {            permissions = this.rolePermissionService.getPermissionByRole(roles);        }        info.setStringPermissions(permissions);        return info;    }    /**     *      * 1、CAS认证 ,验证用户身份     * 2、将用户基本信息设置到会话中     */    @Override    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {        //调用父类的方法,然后授权用户        AuthenticationInfo authc = super.doGetAuthenticationInfo(token);        //获取用户名        String username = (String) authc.getPrincipals().getPrimaryPrincipal();        //数据库中,查询用户的信息        User user = userService.login(username);        SecurityUtils.getSubject().getSession().setAttribute("user", user);        return authc;    }}

3、配置访问的地址,shiro.properties

#localhost#yellowcong.com 表示的是cas的认证地址 ,需要同tomcat生成的SSL的域名一致#127.0.0.1 这个相当与调用Cas服务的客户端了,不需要认证 的域名#登录地址shiro.loginUrl=https://yellowcong.com:8443/cas/login?service=http://127.0.0.1:8080/test_cas/cas/login#登出地址shiro.logoutUrl=https://yellowcong.com:8443/cas/logout?service=http://127.0.0.1:8080/test_cas/cas/loginOut#服务器前缀shiro.cas.serverUrlPrefix=https://yellowcong.com:8443/cas#客户端的cas 服务地址shiro.cas.service=http://127.0.0.1:8080/test_cas/cas/login#登录失败地址shiro.failureUrl=/user/error#登录成功地址shiro.successUrl=/user/list

4、配置spring.xml导入properties

<!-- 引入属性文件 -->     <bean id="propertyConfigurer"        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">        <!-- 除了支持配置的properties文件外,还支持系统属性        SYSTEM_PROPERTIES_MODE_OVERRIDE   //系统属性可以被覆盖        SYSTEM_PROPERTIES_MODE_NEVER  //不检测系统属性        SYSTEM_PROPERTIES_MODE_FALLBACK  // 这个是默认的配置        -->        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />         <!-- 里面配置的properties文件如果找不到的话,就可以忽略找不到的文件 -->        <property name="ignoreResourceNotFound" value="true" />        <property name="locations">            <list>                <value>classpath:jdbc.properties</value>                <value>classpath:shiro.properties</value>            </list>        </property>    </bean>

5、配置spring-shiro.xml文件

<?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:aop="http://www.springframework.org/schema/aop"    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"    xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">    <description>== Shiro Components ==</description>    <!-- 给予shior的内存缓存系统 ,这个是shiro的缓存服务-->    <!-- <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />       -->     <!--           配置 CacheManager.     -->         <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">        <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>     </bean>    <!-- 安全管理器 -->        <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">          <!-- 缓存管理器 -->        <property name="cacheManager" ref="cacheManager" />          <!-- 验证 -->                <property name="authenticator" ref="authenticator"/>        <!-- 多个验证策略 realmes -->        <property name="realms">            <list>                <!-- 这个认证,有一个先后的顺序 -->                <ref bean="casRealm"/>            </list>        </property>        <property name="subjectFactory" ref="casSubjectFactory"/>    </bean>      <!-- 会话Cookie模板 -->    <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">        <constructor-arg value="sid"/>        <property name="httpOnly" value="true"/>        <property name="maxAge" value="-1"/>    </bean>    <!-- 授权策略 -->    <bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">        <property name="authenticationStrategy" >            <!-- 所有Reaml都全部匹配的策略 -->            <!-- <bean class="org.apache.shiro.authc.pam.AllSuccessfulStrategy"/> -->            <bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"/>        </property>    </bean>    <!-- 定义cas授权的Real,也是需要几层 -->    <bean id="casRealm" class="com.yellowcong.shiro.realm.WebCasRealm">        <!-- 认证通过后的默认角色 -->        <property name="defaultRoles" value="ROLE_USER" />        <!-- cas服务端地址前缀 -->        <property name="casServerUrlPrefix" value="${shiro.cas.serverUrlPrefix}" />        <!-- 应用服务地址,用来接收cas服务端票据 -->        <property name="casService" value="${shiro.cas.service}" />    </bean>    <!-- 登录过滤器 -->    <bean id="casFilter" class="org.apache.shiro.cas.CasFilter">        <!-- 配置验证错误时的失败页面 -->        <property name="failureUrl" value="${shiro.failureUrl}" />        <property name="successUrl" value="${shiro.successUrl}" />    </bean>    <!-- 登出过滤器 -->    <bean id="logoutFilter" class="org.apache.shiro.web.filter.authc.LogoutFilter">        <!-- 配置验证错误时的失败页面 -->        <property name="redirectUrl" value="${shiro.logoutUrl}" />    </bean>    <!-- Shior的过滤器配置 -->    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">         <property name="securityManager" ref="securityManager" />       <!-- 设定用户的登录链接,这里为cas登录页面的链接地址可配置回调地址 -->       <property name="loginUrl" value="${shiro.loginUrl}" />       <!-- 设定过滤器 -->       <property name="filters">            <map>                <!-- 添加casFilter到shiroFilter -->                <entry key="casFilter" value-ref="casFilter" />                <entry key="logoutFilter" value-ref="logoutFilter" />            </map>        </property>        <property name="filterChainDefinitions">            <value> <!-- 设置访问用户list页面需要授权操作 -->                /cas/login = casFilter                /cas/loginOut = logoutFilter                /user/error = anon                 /users/user/login = anon <!-- 配置js和img这些静态资源被任何人访问到 -->                /resources/img/** = anon                 /resources/js/** = anon                /** = user            </value>        </property>   </bean>    <bean id="casSubjectFactory" class="org.apache.shiro.cas.CasSubjectFactory"/></beans>

5、配置登出的监听器和拦截器 web.xml

<listener>    <listener-class>org.jasig.cas.client.session.SingleSignOutHttpSessionListener</listener-class>  </listener>  <filter>    <filter-name>singleSignOutFilter</filter-name>    <filter-class>org.jasig.cas.client.session.SingleSignOutFilter</filter-class>  </filter>  <filter-mapping>    <filter-name>singleSignOutFilter</filter-name>    <url-pattern>/*</url-pattern>  </filter-mapping>  <filter>    <filter-name>shiroFilter</filter-name>    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  </filter>  <filter-mapping>    <filter-name>shiroFilter</filter-name>    <url-pattern>/*</url-pattern>    <dispatcher>REQUEST</dispatcher>    <dispatcher>FORWARD</dispatcher>    <dispatcher>INCLUDE</dispatcher>    <dispatcher>ERROR</dispatcher>  </filter-mapping>

测试

1、登录node1

http://127.0.0.1:8080/test_cas/user/login

2、输入数据到cas
转发到了cas服务端
这里写图片描述

3、跳转到目标服务器端
这里写图片描述

错误集合

SLL证书错误

javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names present
这里写图片描述

导致这个问题的原因是我直接通过ip地址对服务器进行访问。换成域名访问就可以解决这个问题了。
这里写图片描述

修改hosts

C:\Windows\System32\drivers\etc

这里写图片描述

添加ssl的匹配的名称
这里写图片描述

参考文章

https://www.cnblogs.com/coderhuang/p/5897444.html

原创粉丝点击