单独启用spring-security配置和spring-security集成cas配置

一:单独启用配置思路:
spring-security.xml:
1.配置路径对应的权限
2.配置用户权限授权

web.xml:
1.配置spring-security过滤器
2.配置spring-security监听器,防止session固话攻击和session并发控制

二:spring-security集成cas配置思路:
spring-security-cas.xml:
1.配置路径对应的权限
2.把cas的认证配置集成到这里来(即登录认证路径、认证成功回调地址、ticket校验路径、登出session监听、登出路径,登出成功回调路径等,不在web.xml配置了)
3.角色授权,即用户授权

web.xml不变


一:单独启用配置

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/security
      http://www.springframework.org/schema/security/spring-security-4.2.xsd ">

    <!--不需要权限的资源-->
    <http pattern="/images/**" security="none"/>

    <!--权限过滤-->
    <http auto-config="true" use-expressions="true">

        <!--
            开启防止CSRF攻击
            请求页面要携带指定参数:<input name="${_csrf.parameterName}" type="hidden" value="${_csrf.token}" />
        -->
        <csrf />

        <!--
            所有带有admin的请求都需要Admin权限
            hasRole:拥有什么角色才可以访问
        -->
        <intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')"/>
        <intercept-url pattern="/" access="hasRole('ROLE_ADMIN')"/>
        <intercept-url pattern="/index.jsp" access="hasRole('ROLE_ADMIN')"/>

        <!--
            login-page:自定义登录页面
            login-processing-url:登录校验请求URL
            default-target-url:默认登录成功后跳转的地址
            authentication-failure-url:登录失败跳转的地址
            username-parameter:自定义登录页面,请求的用户名参数(用于后面查数据库校验作用)
            password-parameter:自定义登录页面,请求的密码参数(用于后面查数据库校验作用)
        -->
        <form-login login-page="/login"
                    login-processing-url="/j_spring_security_check"
                    default-target-url="/admin/welcome"
                    authentication-failure-url="/login?error"
                    username-parameter="username"
                    password-parameter="password"/>

        <!--
             退出
             logout-success-url:退出成功跳转URL
             logout-url:退出请求URL
        -->
        <logout logout-success-url="/login?logout"
                logout-url="/j_spring_security_logout" />


    </http>

    <!--授权管理-->
    <authentication-manager>
        <!--&lt;!&ndash;提供账号密码&ndash;&gt;
        <authentication-provider>
            &lt;!&ndash;
                硬编码方式提供账号密码
                authorities:赋予什么角色
            &ndash;&gt;
            &lt;!&ndash;<user-service>
                <user name="admin" authorities="ROLE_ADMIN" password="123456" disabled="false"/>
            </user-service>&ndash;&gt;

            &lt;!&ndash;查数据库方式&ndash;&gt;
            <jdbc-user-service data-source-ref="dataSource"
                               users-by-username-query="select username, password, enabled from users where username=?"/>
        </authentication-provider>-->

        <!--自定义登录校验器-->
        <authentication-provider user-service-ref="loginValidation"/>


    </authentication-manager>

    <beans:bean class="cn.test.security.LoginValidation" id="loginValidation" />

</beans:beans>

 

根据需要,放开注释部分。

/**
 * spring-security自定义登录校验器,必须实现UserDetailsService
 */
public class LoginValidation implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        cn.test.model.User user = userService.getUserByUsername(username);

        List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

        User user1 = new User(user.getUsername(), user.getPassword(),authorities);
        return user1;

        //集成cas后
        /*List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));

        return new User(username,"",authorities);*/
    }
}

 web.xml添加:

  <!--springsecurity过滤器,做资源权限的拦截和验证-->
  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!--
  springsecurity监听
  防止session固话攻击和session并发控制
 -->
  <listener>
    <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
  </listener>

二:spring-security集成cas配置

上面的spring-security.xml全删除,改为spring-security-cas.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                  http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">

    <!--过滤不需要的权限的URL-->
    <http pattern="/images/**" security="none"></http>

    <!--   entry-point-ref  入口点引用 -->
    <http use-expressions="false" entry-point-ref="casProcessingFilterEntryPoint">
        <intercept-url pattern="/**" access="ROLE_USER"/>
        <csrf disabled="true"/>
        <!-- custom-filter为过滤器, position 表示将过滤器放在指定的位置上,before表示放在指定位置之前  ,after表示放在指定的位置之后  -->
        <custom-filter ref="casAuthenticationFilter"  position="CAS_FILTER" />
        <custom-filter ref="requestSingleLogoutFilter" before="LOGOUT_FILTER"/>
        <custom-filter ref="singleLogoutFilter" before="CAS_FILTER"/>
    </http>

    <!-- CAS入口点 开始 -->
    <beans:bean id="casProcessingFilterEntryPoint" class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">
        <!-- 单点登录服务器登录URL -->
        <beans:property name="loginUrl" value="https://www.sso.com:8443/cas/login"/>
        <beans:property name="serviceProperties" ref="serviceProperties"/>
    </beans:bean>
    <beans:bean id="serviceProperties" class="org.springframework.security.cas.ServiceProperties">
        <!--
            service 配置自身工程的根地址+/login/cas
            /login/cas:是spring-security自身定义的,用于cas回调的URL
        -->
        <beans:property name="service" value="/login/cas"/>
    </beans:bean>
    <!-- CAS入口点 结束 -->


    <!-- 认证过滤器 开始 -->
    <beans:bean id="casAuthenticationFilter" class="org.springframework.security.cas.web.CasAuthenticationFilter">
        <beans:property name="authenticationManager" ref="authenticationManager"/>
    </beans:bean>
    <!-- 认证管理器 -->
    <authentication-manager alias="authenticationManager">
        <authentication-provider  ref="casAuthenticationProvider">
        </authentication-provider>
    </authentication-manager>
    <!-- 认证提供者 -->
    <beans:bean id="casAuthenticationProvider"     class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
        <beans:property name="authenticationUserDetailsService">
            <beans:bean class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
                <beans:constructor-arg ref="userDetailsService" />
            </beans:bean>
        </beans:property>
        <beans:property name="serviceProperties" ref="serviceProperties"/>
        <!-- ticketValidator 为票据验证器 -->
        <beans:property name="ticketValidator">
            <beans:bean class="org.jasig.cas.client.validation.Cas20ServiceTicketValidator">
                <beans:constructor-arg index="0" value="https://www.sso.com:8443/cas"/>
            </beans:bean>
        </beans:property>
        <beans:property name="key" value="an_id_for_this_auth_provider_only"/>
    </beans:bean>
    <!-- 认证类 -->
    <beans:bean id="userDetailsService" class="cn.test.security.LoginValidation"/>

    <!-- 认证过滤器 结束 -->


    <!-- 单点登出  开始  -->

    <!--检测登出 session做相应处理 过滤器-->
    <beans:bean id="singleLogoutFilter" class="org.jasig.cas.client.session.SingleSignOutFilter"/>
    <!-- 经过此配置,当用户在地址栏输入本地工程 /logout/cas  -->
    <beans:bean id="requestSingleLogoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
        <beans:constructor-arg value="https://www.sso.com:8443/cas/logout?service=http://localhost:8080/images/2.jpeg"/>
        <beans:constructor-arg>
            <beans:bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/>
        </beans:constructor-arg>
        <!--本地登出URL spring-security自己定义退出登录本地要访问的URL-->
        <beans:property name="filterProcessesUrl" value="/logout/cas"/>
    </beans:bean>
    <!-- 单点登出  结束 -->

</beans:beans>

 

/**
 * spring-security自定义登录校验器,必须实现UserDetailsService
 */
public class LoginValidation implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        /*cn.test.model.User user = userService.getUserByUsername(username);

        List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

        User user1 = new User(user.getUsername(), user.getPassword(),authorities);
        return user1;*/

        //集成cas后
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));

        return new User(username,"",authorities);
    }
}

补充:访问数据库授权---添加SQL表

CREATE TABLE `users` (
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  `enabled` varchar(50) NOT NULL,
  PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE `authorities` (
  `username` varchar(50) NOT NULL,
  `authority` varchar(50) NOT NULL,
  UNIQUE KEY `ix_auth_username` (`username`,`authority`),
  CONSTRAINT `fk_authorities_users` FOREIGN KEY (`username`) REFERENCES `users` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

这里是简单使用配置。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值