Spring security认证与授权(四)

来源:互联网 发布:ping 域名ip 编辑:程序博客网 时间:2024/06/05 18:52

在第三个实例基础上我做了第四个实例,这个实例很简单。默认情况下,角色名称必须以ROLE_开头,否则spring security框架无法识别,有时这会让人觉得很不爽。当然,这是可以改变的。

第四个实例:

这里只需要在第三个实例上修改applicationContext-security.xml:

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

    xmlns:sec="http://www.springframework.org/schema/security"

    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-2.5.xsd

   http://www.springframework.org/schema/security

   http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">

    <!-- 自动配置模式,拦截所有请求,有ROLE_USER才可以通过 -->

    <sec:httpauto-config="true"access-decision-manager-ref="accessDecisionManager">

        <sec:intercept-urlpattern="/login.jsp" filters="none"/>

        <!-- 增加ROLE_ADMIN角色-->

        <sec:intercept-urlpattern="/admin.jsp"access="AUTH_ADMIN"/>

        <sec:intercept-urlpattern="/**"access="AUTH_USER"/>

        <sec:form-loginlogin-page="/login.jsp"authentication-failure-url="/login.jsp?login_error=1"/> 

 

    </sec:http>

     <sec:authentication-provider>

            <sec:user-service>

                                <!-- 添加ROLE_ADMIN角色 -->

                <sec:username="admin"password="admin"authorities="AUTH_USER,AUTH_ADMIN"/>

                <sec:username="sharp"password="sharp"authorities="AUTH_USER"/>

            </sec:user-service>

    </sec:authentication-provider>

    <!-- 认证管理器。用户名密码都集成在配置文件中 -->

    <sec:authentication-manageralias="authenticationManager"/>

    <beanid="accessDecisionManager"class="org.springframework.security.vote.AffirmativeBased">

       <propertyname="decisionVoters">

           <list>

              <beanclass="org.springframework.security.vote.RoleVoter">

                  <propertyname="rolePrefix"value="AUTH_"/>

              </bean>

           </list>

       </property>

        </bean>

   

     <!-- 指定中文资源,不是必须的。如果没有这个bean,则有关springSecurity的提示会是英文     -->

     <beanid="messageSource"

       class="org.springframework.context.support.ReloadableResourceBundleMessageSource">

        <propertyname="basename" value="classpath:org/springframework/security/messages_zh_CN"/> 

     </bean>

 

</beans>

就是这一行

<property name="rolePrefix" value="AUTH_"/>

你可以将前缀修改为自己想要的。

不知不觉说了四个实例,不过,这些实例真的是太简单了,而且没什么实际意义,但是,对于开始接触Spring Security的童鞋还是很有帮助的。

在实际的应用中,我们都会将Spring Security与数据库结合。接下来,我们引入数据库继续学习Spring security。

原创粉丝点击